var Rht=Object.defineProperty;var Iht=(s,e,t)=>e in s?Rht(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Pht=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ke=(s,e,t)=>Iht(s,typeof e!="symbol"?e+"":e,t);var Upi=Pht((Xf,Yf)=>{(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const n of r)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function t(r){const n={};return r.integrity&&(n.integrity=r.integrity),r.referrerPolicy&&(n.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?n.credentials="include":r.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function i(r){if(r.ep)return;r.ep=!0;const n=t(r);fetch(r.href,n)}})();var Xt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function tz(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function rNe(s){if(s.__esModule)return s;var e=s.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(i){var r=Object.getOwnPropertyDescriptor(s,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return s[i]}})}),t}var Ime={exports:{}},sNe=function(e,t){return function(){for(var r=new Array(arguments.length),n=0;n"u"}function Dht(s){return s!==null&&!H$(s)&&s.constructor!==null&&!H$(s.constructor)&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}var nNe=ZE("ArrayBuffer");function Lht(s){var e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&nNe(s.buffer),e}function Oht(s){return typeof s=="string"}function Nht(s){return typeof s=="number"}function aNe(s){return s!==null&&typeof s=="object"}function zQ(s){if(wme(s)!=="object")return!1;var e=Object.getPrototypeOf(s);return e===null||e===Object.prototype}var Fht=ZE("Date"),Bht=ZE("File"),kht=ZE("Blob"),Uht=ZE("FileList");function Lme(s){return Pme.call(s)==="[object Function]"}function zht(s){return aNe(s)&&Lme(s.pipe)}function Vht(s){var e="[object FormData]";return s&&(typeof FormData=="function"&&s instanceof FormData||Pme.call(s)===e||Lme(s.toString)&&s.toString()===e)}var Ght=ZE("URLSearchParams");function Wht(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")}function Kht(){return typeof navigator<"u"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window<"u"&&typeof document<"u"}function Ome(s,e){if(!(s===null||typeof s>"u"))if(typeof s!="object"&&(s=[s]),Dme(s))for(var t=0,i=s.length;t0;)n=i[r],a[n]||(e[n]=s[n],a[n]=!0);s=Object.getPrototypeOf(s)}while(s&&(!t||t(s,e))&&s!==Object.prototype);return e}function Qht(s,e,t){s=String(s),(t===void 0||t>s.length)&&(t=s.length),t-=e.length;var i=s.indexOf(e,t);return i!==-1&&i===t}function $ht(s){if(!s)return null;var e=s.length;if(H$(e))return null;for(var t=new Array(e);e-- >0;)t[e]=s[e];return t}var Zht=function(s){return function(e){return s&&e instanceof s}}(typeof Uint8Array<"u"&&Object.getPrototypeOf(Uint8Array)),zu={isArray:Dme,isArrayBuffer:nNe,isBuffer:Dht,isFormData:Vht,isArrayBufferView:Lht,isString:Oht,isNumber:Nht,isObject:aNe,isPlainObject:zQ,isUndefined:H$,isDate:Fht,isFile:Bht,isBlob:kht,isFunction:Lme,isStream:zht,isURLSearchParams:Ght,isStandardBrowserEnv:Kht,forEach:Ome,merge:Qce,extend:Hht,trim:Wht,stripBOM:jht,inherits:Xht,toFlatObject:Yht,kindOf:wme,kindOfTest:ZE,endsWith:Qht,toArray:$ht,isTypedArray:Zht,isFileList:Uht},MI=zu;function E6e(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var oNe=function(e,t,i){if(!t)return e;var r;if(i)r=i(t);else if(MI.isURLSearchParams(t))r=t.toString();else{var n=[];MI.forEach(t,function(l,c){l===null||typeof l>"u"||(MI.isArray(l)?c=c+"[]":l=[l],MI.forEach(l,function(h){MI.isDate(h)?h=h.toISOString():MI.isObject(h)&&(h=JSON.stringify(h)),n.push(E6e(c)+"="+E6e(h))}))}),r=n.join("&")}if(r){var a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+r}return e},qht=zu;function fJ(){this.handlers=[]}fJ.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1};fJ.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};fJ.prototype.forEach=function(e){qht.forEach(this.handlers,function(i){i!==null&&e(i)})};var Jht=fJ,edt=zu,tdt=function(e,t){edt.forEach(e,function(r,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[n])})},lNe=zu;function YP(s,e,t,i,r){Error.call(this),this.message=s,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),i&&(this.request=i),r&&(this.response=r)}lNe.inherits(YP,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var cNe=YP.prototype,uNe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach(function(s){uNe[s]={value:s}});Object.defineProperties(YP,uNe);Object.defineProperty(cNe,"isAxiosError",{value:!0});YP.from=function(s,e,t,i,r,n){var a=Object.create(cNe);return lNe.toFlatObject(s,a,function(l){return l!==Error.prototype}),YP.call(a,s.message,e,t,i,r),a.name=s.name,n&&Object.assign(a,n),a};var Ww=YP,hNe={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},_m=zu;function idt(s,e){e=e||new FormData;var t=[];function i(n){return n===null?"":_m.isDate(n)?n.toISOString():_m.isArrayBuffer(n)||_m.isTypedArray(n)?typeof Blob=="function"?new Blob([n]):Buffer.from(n):n}function r(n,a){if(_m.isPlainObject(n)||_m.isArray(n)){if(t.indexOf(n)!==-1)throw Error("Circular reference detected in "+a);t.push(n),_m.forEach(n,function(l,c){if(!_m.isUndefined(l)){var u=a?a+"."+c:c,h;if(l&&!a&&typeof l=="object"){if(_m.endsWith(c,"{}"))l=JSON.stringify(l);else if(_m.endsWith(c,"[]")&&(h=_m.toArray(l))){h.forEach(function(d){!_m.isUndefined(d)&&e.append(u,i(d))});return}}r(l,u)}}),t.pop()}else e.append(a,i(n))}return r(s),e}var dNe=idt,mse,T6e;function rdt(){if(T6e)return mse;T6e=1;var s=Ww;return mse=function(t,i,r){var n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):i(new s("Request failed with status code "+r.status,[s.ERR_BAD_REQUEST,s.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))},mse}var gse,M6e;function sdt(){if(M6e)return gse;M6e=1;var s=zu;return gse=s.isStandardBrowserEnv()?function(){return{write:function(i,r,n,a,o,l){var c=[];c.push(i+"="+encodeURIComponent(r)),s.isNumber(n)&&c.push("expires="+new Date(n).toGMTString()),s.isString(a)&&c.push("path="+a),s.isString(o)&&c.push("domain="+o),l===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(i){var r=document.cookie.match(new RegExp("(^|;\\s*)("+i+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(i){this.write(i,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),gse}var ndt=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},adt=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},odt=ndt,ldt=adt,fNe=function(e,t){return e&&!odt(t)?ldt(e,t):t},_se,R6e;function cdt(){if(R6e)return _se;R6e=1;var s=zu,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return _se=function(i){var r={},n,a,o;return i&&s.forEach(i.split(` `),function(c){if(o=c.indexOf(":"),n=s.trim(c.substr(0,o)).toLowerCase(),a=s.trim(c.substr(o+1)),n){if(r[n]&&e.indexOf(n)>=0)return;n==="set-cookie"?r[n]=(r[n]?r[n]:[]).concat([a]):r[n]=r[n]?r[n]+", "+a:a}}),r},_se}var vse,I6e;function udt(){if(I6e)return vse;I6e=1;var s=zu;return vse=s.isStandardBrowserEnv()?function(){var t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a"),r;function n(a){var o=a;return t&&(i.setAttribute("href",o),o=i.href),i.setAttribute("href",o),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:i.pathname.charAt(0)==="/"?i.pathname:"/"+i.pathname}}return r=n(window.location.href),function(o){var l=s.isString(o)?n(o):o;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}(),vse}var yse,P6e;function pJ(){if(P6e)return yse;P6e=1;var s=Ww,e=zu;function t(i){s.call(this,i??"canceled",s.ERR_CANCELED),this.name="CanceledError"}return e.inherits(t,s,{__CANCEL__:!0}),yse=t,yse}var xse,w6e;function hdt(){return w6e||(w6e=1,xse=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),xse}var Ase,D6e;function L6e(){if(D6e)return Ase;D6e=1;var s=zu,e=rdt(),t=sdt(),i=oNe,r=fNe,n=cdt(),a=udt(),o=hNe,l=Ww,c=pJ(),u=hdt();return Ase=function(d){return new Promise(function(p,m){var g=d.data,_=d.headers,y=d.responseType,v;function x(){d.cancelToken&&d.cancelToken.unsubscribe(v),d.signal&&d.signal.removeEventListener("abort",v)}s.isFormData(g)&&s.isStandardBrowserEnv()&&delete _["Content-Type"];var A=new XMLHttpRequest;if(d.auth){var b=d.auth.username||"",C=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";_.Authorization="Basic "+btoa(b+":"+C)}var T=r(d.baseURL,d.url);A.open(d.method.toUpperCase(),i(T,d.params,d.paramsSerializer),!0),A.timeout=d.timeout;function w(){if(A){var R="getAllResponseHeaders"in A?n(A.getAllResponseHeaders()):null,I=!y||y==="text"||y==="json"?A.responseText:A.response,L={data:I,status:A.status,statusText:A.statusText,headers:R,config:d,request:A};e(function(V){p(V),x()},function(V){m(V),x()},L),A=null}}if("onloadend"in A?A.onloadend=w:A.onreadystatechange=function(){!A||A.readyState!==4||A.status===0&&!(A.responseURL&&A.responseURL.indexOf("file:")===0)||setTimeout(w)},A.onabort=function(){A&&(m(new l("Request aborted",l.ECONNABORTED,d,A)),A=null)},A.onerror=function(){m(new l("Network Error",l.ERR_NETWORK,d,A,A)),A=null},A.ontimeout=function(){var I=d.timeout?"timeout of "+d.timeout+"ms exceeded":"timeout exceeded",L=d.transitional||o;d.timeoutErrorMessage&&(I=d.timeoutErrorMessage),m(new l(I,L.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,d,A)),A=null},s.isStandardBrowserEnv()){var P=(d.withCredentials||a(T))&&d.xsrfCookieName?t.read(d.xsrfCookieName):void 0;P&&(_[d.xsrfHeaderName]=P)}"setRequestHeader"in A&&s.forEach(_,function(I,L){typeof g>"u"&&L.toLowerCase()==="content-type"?delete _[L]:A.setRequestHeader(L,I)}),s.isUndefined(d.withCredentials)||(A.withCredentials=!!d.withCredentials),y&&y!=="json"&&(A.responseType=d.responseType),typeof d.onDownloadProgress=="function"&&A.addEventListener("progress",d.onDownloadProgress),typeof d.onUploadProgress=="function"&&A.upload&&A.upload.addEventListener("progress",d.onUploadProgress),(d.cancelToken||d.signal)&&(v=function(R){A&&(m(!R||R&&R.type?new c:R),A.abort(),A=null)},d.cancelToken&&d.cancelToken.subscribe(v),d.signal&&(d.signal.aborted?v():d.signal.addEventListener("abort",v))),g||(g=null);var M=u(T);if(M&&["http","https","file"].indexOf(M)===-1){m(new l("Unsupported protocol "+M+":",l.ERR_BAD_REQUEST,d));return}A.send(g)})},Ase}var bse,O6e;function ddt(){return O6e||(O6e=1,bse=null),bse}var qc=zu,N6e=tdt,F6e=Ww,fdt=hNe,pdt=dNe,mdt={"Content-Type":"application/x-www-form-urlencoded"};function B6e(s,e){!qc.isUndefined(s)&&qc.isUndefined(s["Content-Type"])&&(s["Content-Type"]=e)}function gdt(){var s;return(typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(s=L6e()),s}function _dt(s,e,t){if(qc.isString(s))try{return(e||JSON.parse)(s),qc.trim(s)}catch(i){if(i.name!=="SyntaxError")throw i}return(0,JSON.stringify)(s)}var mJ={transitional:fdt,adapter:gdt(),transformRequest:[function(e,t){if(N6e(t,"Accept"),N6e(t,"Content-Type"),qc.isFormData(e)||qc.isArrayBuffer(e)||qc.isBuffer(e)||qc.isStream(e)||qc.isFile(e)||qc.isBlob(e))return e;if(qc.isArrayBufferView(e))return e.buffer;if(qc.isURLSearchParams(e))return B6e(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i=qc.isObject(e),r=t&&t["Content-Type"],n;if((n=qc.isFileList(e))||i&&r==="multipart/form-data"){var a=this.env&&this.env.FormData;return pdt(n?{"files[]":e}:e,a&&new a)}else if(i||r==="application/json")return B6e(t,"application/json"),_dt(e);return e}],transformResponse:[function(e){var t=this.transitional||mJ.transitional,i=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,n=!i&&this.responseType==="json";if(n||r&&qc.isString(e)&&e.length)try{return JSON.parse(e)}catch(a){if(n)throw a.name==="SyntaxError"?F6e.from(a,F6e.ERR_BAD_RESPONSE,this,null,this.response):a}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ddt()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};qc.forEach(["delete","get","head"],function(e){mJ.headers[e]={}});qc.forEach(["post","put","patch"],function(e){mJ.headers[e]=qc.merge(mdt)});var Nme=mJ,vdt=zu,ydt=Nme,xdt=function(e,t,i){var r=this||ydt;return vdt.forEach(i,function(a){e=a.call(r,e,t)}),e},Cse,k6e;function pNe(){return k6e||(k6e=1,Cse=function(e){return!!(e&&e.__CANCEL__)}),Cse}var U6e=zu,Sse=xdt,Adt=pNe(),bdt=Nme,Cdt=pJ();function Ese(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Cdt}var Sdt=function(e){Ese(e),e.headers=e.headers||{},e.data=Sse.call(e,e.data,e.headers,e.transformRequest),e.headers=U6e.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),U6e.forEach(["delete","get","head","post","put","patch","common"],function(r){delete e.headers[r]});var t=e.adapter||bdt.adapter;return t(e).then(function(r){return Ese(e),r.data=Sse.call(e,r.data,r.headers,e.transformResponse),r},function(r){return Adt(r)||(Ese(e),r&&r.response&&(r.response.data=Sse.call(e,r.response.data,r.response.headers,e.transformResponse))),Promise.reject(r)})},Rf=zu,mNe=function(e,t){t=t||{};var i={};function r(u,h){return Rf.isPlainObject(u)&&Rf.isPlainObject(h)?Rf.merge(u,h):Rf.isPlainObject(h)?Rf.merge({},h):Rf.isArray(h)?h.slice():h}function n(u){if(Rf.isUndefined(t[u])){if(!Rf.isUndefined(e[u]))return r(void 0,e[u])}else return r(e[u],t[u])}function a(u){if(!Rf.isUndefined(t[u]))return r(void 0,t[u])}function o(u){if(Rf.isUndefined(t[u])){if(!Rf.isUndefined(e[u]))return r(void 0,e[u])}else return r(void 0,t[u])}function l(u){if(u in t)return r(e[u],t[u]);if(u in e)return r(void 0,e[u])}var c={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:l};return Rf.forEach(Object.keys(e).concat(Object.keys(t)),function(h){var d=c[h]||n,f=d(h);Rf.isUndefined(f)&&d!==l||(i[h]=f)}),i},Tse,z6e;function gNe(){return z6e||(z6e=1,Tse={version:"0.27.2"}),Tse}var Edt=gNe().version,by=Ww,Fme={};["object","boolean","number","function","string","symbol"].forEach(function(s,e){Fme[s]=function(i){return typeof i===s||"a"+(e<1?"n ":" ")+s}});var V6e={};Fme.transitional=function(e,t,i){function r(n,a){return"[Axios v"+Edt+"] Transitional option '"+n+"'"+a+(i?". "+i:"")}return function(n,a,o){if(e===!1)throw new by(r(a," has been removed"+(t?" in "+t:"")),by.ERR_DEPRECATED);return t&&!V6e[a]&&(V6e[a]=!0,console.warn(r(a," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(n,a,o):!0}};function Tdt(s,e,t){if(typeof s!="object")throw new by("options must be an object",by.ERR_BAD_OPTION_VALUE);for(var i=Object.keys(s),r=i.length;r-- >0;){var n=i[r],a=e[n];if(a){var o=s[n],l=o===void 0||a(o,n,s);if(l!==!0)throw new by("option "+n+" must be "+l,by.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new by("Unknown option "+n,by.ERR_BAD_OPTION)}}var Mdt={assertOptions:Tdt,validators:Fme},_Ne=zu,Rdt=oNe,G6e=Jht,W6e=Sdt,gJ=mNe,Idt=fNe,vNe=Mdt,RI=vNe.validators;function QP(s){this.defaults=s,this.interceptors={request:new G6e,response:new G6e}}QP.prototype.request=function(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=gJ(this.defaults,t),t.method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;i!==void 0&&vNe.assertOptions(i,{silentJSONParsing:RI.transitional(RI.boolean),forcedJSONParsing:RI.transitional(RI.boolean),clarifyTimeoutError:RI.transitional(RI.boolean)},!1);var r=[],n=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(t)===!1||(n=n&&f.synchronous,r.unshift(f.fulfilled,f.rejected))});var a=[];this.interceptors.response.forEach(function(f){a.push(f.fulfilled,f.rejected)});var o;if(!n){var l=[W6e,void 0];for(Array.prototype.unshift.apply(l,r),l=l.concat(a),o=Promise.resolve(t);l.length;)o=o.then(l.shift(),l.shift());return o}for(var c=t;r.length;){var u=r.shift(),h=r.shift();try{c=u(c)}catch(d){h(d);break}}try{o=W6e(c)}catch(d){return Promise.reject(d)}for(;a.length;)o=o.then(a.shift(),a.shift());return o};QP.prototype.getUri=function(e){e=gJ(this.defaults,e);var t=Idt(e.baseURL,e.url);return Rdt(t,e.params,e.paramsSerializer)};_Ne.forEach(["delete","get","head","options"],function(e){QP.prototype[e]=function(t,i){return this.request(gJ(i||{},{method:e,url:t,data:(i||{}).data}))}});_Ne.forEach(["post","put","patch"],function(e){function t(i){return function(n,a,o){return this.request(gJ(o||{},{method:e,headers:i?{"Content-Type":"multipart/form-data"}:{},url:n,data:a}))}}QP.prototype[e]=t(),QP.prototype[e+"Form"]=t(!0)});var Pdt=QP,Mse,K6e;function wdt(){if(K6e)return Mse;K6e=1;var s=pJ();function e(t){if(typeof t!="function")throw new TypeError("executor must be a function.");var i;this.promise=new Promise(function(a){i=a});var r=this;this.promise.then(function(n){if(r._listeners){var a,o=r._listeners.length;for(a=0;a{i.style.display="none",QX=null},e)}function Udt(s){const e=document.getElementById("login-wrap");e.style.display="flex";const t=document.getElementById("login-btn"),i=async()=>{await s()&&(t.removeEventListener("click",i),e.style.display="none")};t.addEventListener("click",i)}function CS(s,e){const t=e||new Path2D;let i=s.calculative.borderRadius||0,r=i;const{x:n,y:a,width:o,height:l,ex:c,ey:u}=s.calculative.worldRect;i<1&&(i=o*i,r=l*r);let h=i(s[s.Node=0]="Node",s[s.Line=1]="Line",s))(Kn||{}),qs=(s=>(s[s.None=0]="None",s[s.DisableEdit=1]="DisableEdit",s[s.DisableMove=2]="DisableMove",s[s.DisableScale=3]="DisableScale",s[s.DisableMoveScale=4]="DisableMoveScale",s[s.Disable=10]="Disable",s))(qs||{}),Pk=(s=>(s[s.None=0]="None",s[s.Linear=1]="Linear",s[s.Radial=2]="Radial",s))(Pk||{}),hn=(s=>(s[s.CanvasTemplate=1]="CanvasTemplate",s[s.CanvasImageBottom=2]="CanvasImageBottom",s[s.CanvasMain=3]="CanvasMain",s[s.CanvasImage=4]="CanvasImage",s))(hn||{});const Gdt=["text","textWidth","textHeight","textLeft","textTop","fontFamily","fontSize","lineHeight","fontStyle","fontWeight","textAlign","textBaseline","whiteSpace","ellipsis","keepDecimal"],Wdt=["x","y","width","height","flipX","flipY"],Kdt=["paddingTop","paddingRight","paddingBottom","paddingLeft","flipX","flipY","visible","showChild"],Hdt=["iconLeft","iconTop","iconRotate"];var u0=(s=>(s[s.Normal=0]="Normal",s[s.Beads=1]="Beads",s[s.Dot=2]="Dot",s[s.Arrow=3]="Arrow",s[s.WaterDrop=4]="WaterDrop",s))(u0||{});const xNe=["gif","iframe","video","echarts","highcharts","lightningCharts","vue"],Pse=["radio","checkbox","button","inputDom","slider","echarts"],_9=new Set(["borderRadius","paddingLeft","paddingRight","paddingTop","paddingBottom","progress","progressColor","verticalProgress","reverseProgress","flipX","flipY","input","lineDash","lineCap","lineJoin","strokeType","lineGradientFromColor","lineGradientToColor","lineGradientAngle","color","hoverColor","activeColor","lineWidth","bkType","gradientFromColor","gradientToColor","gradientAngle","gradientRadius","hoverBackground","activeBackground","globalAlpha","anchorColor","anchorRadius","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","textHasShadow","fontFamily","fontSize","textColor","hoverTextColor","activeTextColor","textBackground","fontStyle","fontWeight","textAlign","textBaseline","lineHeight","whiteSpace","textWidth","textHeight","textLeft","textTop","ellipsis","hiddenText","keepDecimal","borderWidth","borderColor","animateLineWidth","lineAnimateType","frames","animateColor","animateType","animateReverse","background","gradientColors","lineGradientColors","animateLineWidth","gradientSmooth","lineSmooth","animations"]);function jdt(s){s.onAdd=void 0,s.onValue=void 0,s.onBeforeValue=void 0,s.onDestroy=void 0,s.onMove=void 0,s.onResize=void 0,s.onRotate=void 0,s.onClick=void 0,s.onMouseEnter=void 0,s.onMouseLeave=void 0,s.onMouseDown=void 0,s.onMouseMove=void 0,s.onMouseUp=void 0,s.onShowInput=void 0,s.onInput=void 0,s.onChangeId=void 0,s.onBinds=void 0,s.onStartVideo=void 0,s.onPauseVideo=void 0,s.onStopVideo=void 0,s.onRenderPenRaw=void 0,s.onKeyDown=void 0,s.onContextmenu=void 0,s.onScale=void 0,s.onWheel=void 0,s.onConnectLine=void 0}var pr=(s=>(s[s.None=0]="None",s[s.LineAnchor=1]="LineAnchor",s[s.NodeAnchor=2]="NodeAnchor",s[s.Line=3]="Line",s[s.Node=4]="Node",s[s.Resize=5]="Resize",s[s.Rotate=6]="Rotate",s[s.LineAnchorPrev=7]="LineAnchorPrev",s[s.LineAnchorNext=8]="LineAnchorNext",s))(pr||{}),ia=(s=>(s[s.None=0]="None",s[s.Translate=1]="Translate",s[s.Select=2]="Select",s[s.Resize=3]="Resize",s[s.AddAnchor=4]="AddAnchor",s))(ia||{}),gy=(s=>(s[s.None=0]="None",s[s.Down=1]="Down",s[s.Translate=2]="Translate",s))(gy||{}),Ts=(s=>(s[s.None=-1]="None",s[s.Up=0]="Up",s[s.Right=1]="Right",s[s.Bottom=2]="Bottom",s[s.Left=3]="Left",s))(Ts||{});const Y6e=["nw-resize","ne-resize","se-resize","sw-resize"],Q6e=["n-resize","e-resize","s-resize","w-resize"],Xdt=["curve","polyline","line"],ANe=["dash","lineWidth","lineCap","lineJoin","strokeType","color","lineGradientFromColor","lineGradientToColor","lineGradientAngle","globalAlpha","bkType","background","gradientFromColor","gradientToColor","gradientAngle","gradientRadius","fontFamily","fontSize","textColor","hoverTextColor","activeTextColor","textBackground","fontStyle","fontWeight","textAlign","textBaseline","lineHeight","whiteSpace","textLeft","textTop","flipX","flipY","lineDash","visible","iconColor"];var q5=(s=>(s[s.Mirror=0]="Mirror",s[s.Bilateral=1]="Bilateral",s[s.Free=2]="Free",s))(q5||{}),uh=(s=>(s[s.Default=0]="Default",s[s.In=1]="In",s[s.Out=2]="Out",s[s.DisableConnected=3]="DisableConnected",s[s.DisableConnectTo=4]="DisableConnectTo",s[s.Disable=10]="Disable",s))(uh||{}),WC=(s=>(s[s.Default=0]="Default",s[s.Line=1]="Line",s))(WC||{});function Pa(s,e,t){if(!e||e%360===0)return;const i=e*Math.PI/180,r=(s.x-t.x)*Math.cos(i)-(s.y-t.y)*Math.sin(i)+t.x,n=(s.x-t.x)*Math.sin(i)+(s.y-t.y)*Math.cos(i)+t.y;s.x=r,s.y=n,s.prev&&Pa(s.prev,e,t),s.next&&Pa(s.next,e,t)}function g5(s,e,t=5,i){if(e.type===1){let r=i.rotate;i.flipX&&(r*=-1),i.flipY&&(r*=-1);let n=e.rotate+r;return i.flipX&&(n*=-1),i.flipY&&(n*=-1),vy(s,{x:e.x-e.length*i.calculative.canvas.store.data.scale/2,y:e.y-t,width:e.length*i.calculative.canvas.store.data.scale,height:t*2,rotate:n})}else return s.x>e.x-t&&s.xe.y-t&&s.y0&&i>0?r=180-r:t<0&&i>0?r+=180:t<0&&i<0&&(r=360-r),r}function _J(s,e){const t=s.x-e.x,i=s.y-e.y;return Math.sqrt(t*t+i*i)}function Ydt(s,e){let t=Ts.None;if(!e)return t;const i=s.x-e.x,r=s.y-e.y;return Math.abs(i)>Math.abs(r)?i>0?t=Ts.Right:t=Ts.Left:r>0?t=Ts.Bottom:t=Ts.Up,t}function BB(s,e,t){s&&(s.x+=e,s.y+=t,s.next&&(s.next.x+=e,s.next.y+=t),s.prev&&(s.prev.x+=e,s.prev.y+=t))}function $6e(s,e){return s.anchorId===e.anchorId&&s.connectTo===e.connectTo}function $X(s,e,t){let i=Math.sqrt((s.x-e.x)*(s.x-e.x)+(s.y-e.y)*(s.y-e.y))/t.data.scale;e.rotate===0?s.x>>0,1)},emit:function(e,t){(s.get(e)||[]).slice().map(function(i){i(t)}),(s.get("*")||[]).slice().map(function(i){i(e,t)})}}}var fB=(s=>(s[s.None=-1]="None",s[s.Document=0]="Document",s[s.Canvas=1]="Canvas",s))(fB||{});const dft={fontFamily:'"Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial',fontSize:12,lineHeight:1.5,textAlign:"center",textBaseline:"middle",color:"#222222",activeColor:"#278df8",hoverColor:"rgba(39,141,248,0.50)",anchorColor:"#278DF8",hoverAnchorColor:"#FF4101",anchorRadius:4,anchorBackground:"#fff",dockColor:"rgba(39,141,248,0.50)",dockPenColor:"#1890FF",dragColor:"#1890ff",rotateCursor:"rotate.cur",rightCursor:"right.cur",downCursor:"down.cur",hoverCursor:"pointer",minScale:.1,maxScale:10,keydown:0,gridSize:20,gridColor:"#e2e2e2",ruleColor:"#888888",drawingLineName:"curve",interval:30,animateInterval:30,autoPolyline:!0,autoAnchor:!0,autoAlignGrid:!1,animateColor:"#30EEDC",ruleLineColor:"#FF4101",shadowOffsetX:0,shadowOffsetY:0,shadowBlur:64,shadowColor:"#00000014",globalAlpha:1,defaultAnchors:[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}],measureTextWidth:!0,moveConnectedLine:!0,mouseRightActive:!0,disableClipboard:!1,drawingLineLength:0,disableTouchPadScale:!1,cdn:"",polylineSpace:10,domShapes:[],containerShapes:["tablePlus"],textFlip:!0,textRotate:!0,unavailableKeys:[],diagramOptions:{},svgPathStroke:!0,reconnetTimes:10},fft=["color","hoverColor","activeColor","disabledColor","background","activeBackground","hoverBackground","disabledBackground","anchorColor","hoverAnchorColor","anchorBackground","animateColor","textColor","ruleColor","ruleLineColor","gridColor","lineColor","penBackground","dockPenColor"],pft={dark:{color:"#bdc7db",background:"#1e2430",parentBackground:"#080b0f",ruleColor:"#222E47",ruleOptions:{background:"#121924",textColor:"#6E7B91"}},light:{color:"#222222",background:"#FFFFFF",parentBackground:"#F0F1F2",ruleColor:"#C8D0E1",ruleOptions:{background:"#F7F8FA",textColor:"#C8D0E1"}}},wse={cssRuleSelector:":root",style_prefix:"le5le_",vendor_css_prefix:"--le-",dark:["text-color-primary: #7f838c","text-color-second: rgba(255,255,255,0.90)","text-color-disabled: rgba(255,255,255,0.40)","container-bg: rgba(21,24,28,0.95)","form-bg: #2a2f36","date-picker-cell-active-with-range-bg: #2c4475","component-disabled-bg-color: #252b37","data-picker-cell-active-bg: #4583ff","active-bg: #25375b","popcontent-bg: #252b37","bdcolor-outside: #4583ff","bdcolor-form: #424b61","bdcolor-inside: rgba(255,255,255,0.40)","shadow: 0px 1px 10px 0px rgba(0,0,0,0.05), 0px 4px 5px 0px rgba(0,0,0,0.08), 0px 2px 4px -1px rgba(0,0,0,0.12)","radius: 4px"],light:["text-color-primary: #7f838c","text-color-second: #171B27","text-color-disabled: rgba(0, 0, 0, 0.6)","container-bg: #ffffff","form-bg: #EFF1F4","date-picker-cell-active-with-range-bg: #f2f3ff","component-disabled-bg-color: #eee","data-picker-cell-active-bg: #0052d9","active-bg: #f2f3ff","popcontent-bg: #ffffff","bdcolor-outside: transparent","bdcolor-form: #d4d6d9","bdcolor-inside: #e7e7e7","shadow: 0px 2px 4px 0px rgba(107,113,121,0.25)","radius: 4px"],_addVendorCssPrefix(s){return s.map(e=>{const[t,i]=e.split(":");return`${this.vendor_css_prefix}${t.trim()}:${i.trim()}`})},createThemeSheet(s,e){const t=document.createElement("style");t.type="text/css",t.id=this.style_prefix+e,document.head.appendChild(t);const i=s||"light",r=this.getTheme(i),n=`${this.cssRuleSelector} { ${r.join(";")} }`;t.innerHTML=n},destroyThemeSheet(s){const e=this.findStyleSheet(this.style_prefix+s);e&&document.head.removeChild(e.ownerNode)},getTheme(s){return this._addVendorCssPrefix(this[s]||this.light)},findStyleSheet(s){const e=document.styleSheets;for(let t=0;to.selectorText===this.cssRuleSelector);if(a){const o=i.join(";");a.style.cssText+=`; ${o}`}else r.addRule(this.cssRuleSelector,i.join(";"))}}};var ur=(s=>(s[s.Add=0]="Add",s[s.Update=1]="Update",s[s.Delete=2]="Delete",s[s.Replace=3]="Replace",s))(ur||{});const mft=()=>({data:{x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{}},histories:[],pens:{},path2dMap:new WeakMap,animateMap:new WeakMap,active:[],animates:new Set,options:{...dft},theme:{...pft},emitter:hft(),bindDatas:{},bind:{},pensNetwork:{},cacheDatas:[],messageEvents:{},templatePens:{},globalTriggers:{}}),gft=(s="default")=>(Lr[s]||(Lr[s]=mft(),Lr[s].id=s),Lr[s]),_ft=(s,e)=>{const t=s.data.template===e;if(t)for(const i of s.data.pens)i.canvasLayer===hn.CanvasTemplate&&(s.templatePens[i.id]=i);s.lastScale=s.data.scale,s.data={x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{},template:t?e:null},s.sameTemplate=t,s.pens={},s.histories=[],s.historyIndex=null,s.path2dMap=new WeakMap,s.animateMap=new WeakMap,s.bindDatas={},s.bind={},s.pensNetwork={},s.active=[],s.hover=void 0,s.lastHover=void 0,s.animates.clear()};function L1(s){const{paddingTop:e,paddingBottom:t,paddingLeft:i,paddingRight:r,worldRect:n,canvas:a}=s.calculative;let{textLeft:o,textTop:l,textWidth:c,textHeight:u}=s.calculative,h=i,d=e;const f=n.width-i-r,p=n.height-e-t;c&&c<1&&(c*=n.width),u&&u<1&&(u*=n.height),c1?a:1;switch(s.whiteSpace){case"nowrap":if(s.ellipsis!==!1){const u=Z6e(e.split(""),s);u[0]&&(i.push(u[0]),u.length>1&&Dse(i))}else i.push(e);break;case"pre-line":i=e.split(/[\n]/g),s.ellipsis!==!1&&i.length>o&&(i=i.slice(0,o),Dse(i));break;case"break-all":default:const l=e.split(/[\n]/g);let c=0;e:for(const u of l){const h=s.whiteSpace==="break-all"?u.split(""):SNe(u);let d=Z6e(h,s);if(d.length===0&&(d=[""]),s.ellipsis!=!1)for(const f of d)if(c++,c>o){Dse(i);break e}else i.push(f);else i.push(...d)}break}return s.calculative.textLines=i,i}function SNe(s=""){const e=[];let t="";for(let i=0;i126?(t&&(e.push(t),t=""),e.push(s[i])):t+=s[i]}return t&&e.push(t),e}function Z6e(s,e){const t=e.calculative.canvas,i=t.offscreen.getContext("2d"),{fontStyle:r,fontWeight:n,fontSize:a,fontFamily:o,lineHeight:l}=e.calculative;i.save();const c=[];let u=s[0]||"";for(let h=1;h{const r=s.measureText(i).width;e.calculative.textLineWidths.push(r),tc&&(c=u)}i.restore();let h=e.length*a*l;s.textAlign==="left"||(s.textAlign==="right"?s.x=s.x-(c-s.width):s.x=s.x-(c-s.width)/2),s.textBaseline==="top"||(s.textBaseline==="bottom"?s.y=s.y-(h-s.height):s.y=s.y-(h-s.height)/2),s.height=h+2,s.width=c+2,s.calculative.canvas.updatePenRect(s),s.calculative.canvas.calcActiveRect()}function bt(s,e=!1){if(Array.isArray(s)){const t=[];return s.forEach(i=>{t.push(bt(i,e))}),t}else if(typeof s=="object"){if(s===null)return null;if(s.constructor===RegExp)return s;const t={};for(const i in s)if(!(["canvas","lastFrame"].includes(i)||s[i]instanceof HTMLImageElement||s[i]instanceof HTMLMediaElement)){{if(i==="calculative"&&!e)continue;if(i==="singleton"){e?t[i]={}:t[i]=s[i];continue}}t[i]=bt(s[i],e)}return t}return s}function Zce(s,e,t){if(Array.isArray(s)){const i=[];return s.forEach(r=>{i.push(Zce(r,e,t))}),i}else if(typeof s=="object"){if(s===null)return null;for(const i in s)if(e.includes(i))if(Array.isArray(s[i]))s[i].forEach((r,n)=>{Number.isNaN(Number(r))||(s[i][n]=Number(r*t))});else{if(Number.isNaN(Number(s[i])))continue;s[i]=Number(s[i])*t}else s[i]=Zce(s[i],e,t);return s}return s}const ip={};function ENe(s,e,t){if(!ip[e.fromArrow])return;const i=rl(e),{x:r,y:n}=i,a={x:r,y:n};if(a.step=(e.fromArrowSize||10)*t.data.scale,i.next)a.rotate=a0(i.next,i)+90;else{const l=e.calculative.worldAnchors[1];if(!l)return;l.prev?a.rotate=a0(l.prev,i)+90:a.rotate=a0(l,i)+90}s.save(),s.beginPath(),s.setLineDash([]);const o=e.fromArrowColor||e.calculative.color;o&&(s.strokeStyle=o),ip[e.fromArrow](s,e,t,a),s.restore()}function TNe(s,e,t){if(!ip[e.toArrow]||e.calculative.worldAnchors.length<2)return;s.save();const i=Dn(e),{x:r,y:n}=i,a={x:r,y:n};if(a.step=(e.toArrowSize||10)*t.data.scale,i.prev)a.rotate=a0(i.prev,i)+90;else{const l=e.calculative.worldAnchors[e.calculative.worldAnchors.length-2];l.next?a.rotate=a0(l.next,i)+90:a.rotate=a0(l,i)+90}s.beginPath(),s.setLineDash([]);const o=e.toArrowColor||e.calculative.color;o&&(s.strokeStyle=o),ip[e.toArrow](s,e,t,a),s.restore()}ip.triangleSolid=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step;s.moveTo(r,i.y-i.step/4),s.lineTo(i.x,i.y),s.lineTo(r,i.y+i.step/4),s.closePath(),s.stroke(),s.fillStyle=s.strokeStyle,s.fill(),s.restore()};ip.triangle=(s,e,t,i)=>{s.save(),s.lineWidth<2&&(s.lineWidth=2),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step;s.moveTo(r,i.y-i.step/4),s.lineTo(i.x,i.y),s.lineTo(r,i.y+i.step/4),s.closePath(),s.stroke(),s.fillStyle=t.data.background||"#ffffff",s.fill(),s.restore()};ip.circleSolid=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.step/2;s.arc(i.x-r,i.y,r,0,2*Math.PI),s.stroke(),s.fillStyle=s.strokeStyle,s.fill(),s.restore()};ip.circle=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.step/2;s.arc(i.x-r,i.y,r,0,2*Math.PI),s.stroke(),s.fillStyle=t.data.background||"#ffffff",s.fill(),s.restore()};ip.diamondSolid=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step,n=i.step/2;s.moveTo(r,i.y),s.lineTo(r+n,i.y-n/2),s.lineTo(i.x,i.y),s.lineTo(r+n,i.y+n/2),s.closePath(),s.stroke(),s.fillStyle=s.strokeStyle,s.fill(),s.restore()};ip.diamond=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step,n=i.step/2;s.moveTo(r,i.y),s.lineTo(r+n,i.y-n/2),s.lineTo(i.x,i.y),s.lineTo(r+n,i.y+n/2),s.closePath(),s.stroke(),s.fillStyle=t.data.background||"#ffffff",s.fill(),s.restore()};ip.line=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step;s.moveTo(r,i.y-i.step/3),s.lineTo(i.x,i.y),s.lineTo(r,i.y+i.step/3),s.stroke(),s.restore()};ip.lineUp=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step;s.moveTo(r,i.y-i.step/3),s.lineTo(i.x,i.y),s.stroke(),s.restore()};ip.lineDown=(s,e,t,i)=>{s.save(),s.translate(i.x,i.y),s.rotate(i.rotate*Math.PI/180),s.translate(-i.x,-i.y);const r=i.x-i.step;s.moveTo(r,i.y+i.step/3),s.lineTo(i.x,i.y),s.stroke(),s.restore()};function qce(s){const e=parseInt,t=Math.round;let i=s.length,r={};if(i>9){const[n,a,o,l]=s=s.split(",");if(i=s.length,i<3||i>4)return null;r.r=e(n[3]=="a"?n.slice(5):n.slice(4)),r.g=e(a),r.b=e(o),r.a=l?parseFloat(l):-1}else{if(i==8||i==6||i<4)return null;i<6&&(s="#"+s[1]+s[1]+s[2]+s[2]+s[3]+s[3]+(i>4?s[4]+s[4]:"")),s=e(s.slice(1),16),i==9||i==5?(r.r=s>>24&255,r.g=s>>16&255,r.b=s>>8&255,r.a=t((s&255)/.255)/1e3):(r.r=s>>16,r.g=s>>8&255,r.b=s&255,r.a=-1)}return r}function Du(s,e,t,i){let r,n,a,o,l,c,u,h=Math.round,d=typeof t=="string";return typeof s!="number"||s<-1||s>1||typeof e!="string"||e[0]!="r"&&e[0]!="#"||t&&!d||(u=e.length>9,u=d?t.length>9?!0:t=="c"?!u:!1:u,l=qce(e),o=s<0,c=t&&t!="c"?qce(t):o?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},s=o?s*-1:s,o=1-s,!l||!c)?null:(i?(r=h(o*l.r+s*c.r),n=h(o*l.g+s*c.g),a=h(o*l.b+s*c.b)):(r=h((o*l.r**2+s*c.r**2)**.5),n=h((o*l.g**2+s*c.g**2)**.5),a=h((o*l.b**2+s*c.b**2)**.5)),d=l.a,c=c.a,l=d>=0||c>=0,d=l?d<0?c:c<0?d:d*o+c*s:0,u?"rgb"+(l?"a(":"(")+r+","+n+","+a+(l?","+h(d*1e3)/1e3:"")+")":"#"+(4294967296+r*16777216+n*65536+a*256+(l?h(d*255):0)).toString(16).slice(1,l?void 0:-2))}globalThis.pSBC=Du;function X$(s,e){const t=qce(s)||{r:0,g:0,b:0};return t.a<0?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(${t.r},${t.g},${t.b},${e+t.a})`}function II(s,e){if(isNaN(s)){console.warn("realValue not number");return}if(typeof e!="string"){console.warn("collection must be string");return}const[t,i]=[e[0],e[e.length-1]];if(!["[","("].includes(t)){console.warn('collection must start with "[" or "("');return}if(!["]",")"].includes(i)){console.warn('collection must end with "]" or ")"');return}const r=e.substring(1,e.length-1).split(",");if(r.length!==2){console.warn("collection must have 2 numbers");return}const[n,a]=[+r[0],+r[1]];if(n>=a){console.warn("startNum must less than endNum");return}return s>n||t==="["&&s===n?s=c){console.warn("startNum must less than endNum");return}if(s>=l&&s<=c)return!0}else if(s==n)return!0;return!1}function fs(){return((1+Math.random())*4294967296|0).toString(16).substring(1)}const rv=s=>{let e=0,t=0,i=0,r=0;return typeof s=="number"?e=t=i=r=s:typeof s=="string"?e=t=i=r=parseInt(s,10):Array.isArray(s)&&(e=s[0],i=Lse(s[1])?s[0]:s[1],r=Lse(s[2])?s[0]:s[2],t=Lse(s[3])?i:s[3]),[e,i,r,t]};function Lse(s){return s==null}async function xft(s){return new Promise((e,t)=>{const i=new FileReader;i.onload=r=>{e(r.target.result)},i.onerror=r=>{t(r)},i.readAsDataURL(s)})}async function Aft(s,e,t,i){const r=new FormData;if(r.append("file",s),t)for(const a in t)t.hasOwnProperty(a)&&r.append(a,t[a]);return(await(await fetch(e,{method:"POST",headers:i,body:r})).json()).url}function bft(s,e,t){var i=document.createElement("link");i.href=s,i.rel="stylesheet",e&&(i.onload=e),document.head.appendChild(i)}function M5(s){let e=s||window.location.search.split("?")[1];const t=new URLSearchParams(e);return Object.fromEntries(t.entries())}function Y$(s){let e;const t=new RegExp("(^| )"+s+"=([^;]*)(;|$)");return(e=document.cookie.match(t))?decodeURIComponent(e[2]):""}const Cft=location.host.indexOf("le5le.com")!==-1;function Sft(){const s=globalThis.le5leTokenName??"token";switch(globalThis.le5leTokenType){case 1:return localStorage.getItem(s);case 2:return Y$(s);default:return Cft?Y$(s):localStorage.getItem(s)}}async function MNe(s,e){var l,c;if(globalThis.getMeta2dData)return await globalThis.getMeta2dData(e);const t=s.options.navigatorNetWork;let r=`/api/data/${location.href.includes("2d.")||location.href.includes("/2d")?"2d":"v"}/get`,n=((l=M5())==null?void 0:l.id)||r.includes("${id}");if(!n&&((c=M5())==null?void 0:c.data)){r=`./projects/${e}`;const h=new URL(window.location);h.searchParams.set("data",e),history.pushState({},"",h)}t!=null&&t.url&&(t.url.includes("${id}")?r=t.url.replace("${id}",e):r=t.url+((t==null?void 0:t.method)==="GET"?`?id=${e}`:""));let a=(t==null?void 0:t.method)||"POST";n||(a="GET");const o=await fetch(r,{headers:{Authorization:`Bearer ${Sft()}`},method:a,body:a==="GET"?void 0:JSON.stringify({id:e})});if(o.ok){let u=await o.text();return u.constructor===Object||u.constructor===Array?u=JSON.parse(JSON.stringify(u)):typeof u=="string"&&(u=JSON.parse(u)),u.data&&(u=u.data),u}else s.emitter.emit("error",{type:"http",error:o})}function oS(s,e){if(e==null)return s;const t=e.split(".");for(;t.length&&(s=s[t.shift()]););return s}function Q$(s,e,t){e!=null&&e.split(".").reduce((i,r,n)=>i[r]=e.split(".").length===++n?t:i[r]||{},s)}function Eft(s){const e=["天","一","二","三","四","五","六"],t=new Date,i=t.getFullYear(),r=t.getMonth()+1,n=t.getDate(),a=t.getDay(),o=t.getHours(),l=t.getMinutes(),c=t.getSeconds();return new Function("year","month","day","week","hours","minutes","seconds",s?`return ${s}`:"return `${year}:${month}:${day} ${hours}:${minutes}:${seconds} 星期${week}`")(i,r,n,e[a],o,l,c)}function Tft(s,e){if(!s||!e)return!1;let t=Uf(s);for(;t;){if(t.id===e.id)return!0;t=Uf(t)}return!1}function Uf(s,e){if(!s||!s.parentId||!s.calculative)return;const i=s.calculative.canvas.store.pens[s.parentId];return e&&Uf(i,e)||i}function S1(s,e){if(!s||!s.children)return[];const t=[];return s.children.forEach(i=>{const r=e.pens[i];r&&(t.push(r),t.push(...S1(r,e)))}),t}function Bme(s,e){if(!s||!s.followers)return[];const t=[];return s.followers.forEach(i=>{const r=e.pens[i];r&&!r.parentId&&(t.push(r),t.push(...Bme(r,e)))}),t}function Mft(s,e){const{worldRect:t,gradientFromColor:i,gradientToColor:r,gradientAngle:n}=e.calculative;return INe(s,t,i,r,n)}function Rft(s,e){const{worldRect:t,gradientFromColor:i,gradientToColor:r,gradientRadius:n}=e.calculative;if(!i||!r)return;const{width:a,height:o,center:l}=t,{x:c,y:u}=l;let h=a;h{f.addColorStop(p.i,p.color)}),f}function wft(s,e){const{x:t,y:i,ex:r,width:n,height:a,center:o}=e.calculative.worldRect;let l=[{x:r,y:i+a/2},{x:t,y:i+a/2}],c=e.calculative.gradientColors;e.calculative.checked&&(c=e.calculative.onGradientColors);const{angle:u,colors:h}=qE(c);let d=kme(u,n,a);return l.forEach(f=>{Pa(f,u,o)}),vJ(s,l,h,d)}function Dft(s,e){const{worldRect:t,textGradientColors:i}=e.calculative;if(!i)return;const{width:r,height:n,center:a}=t,{x:o,y:l}=a;let c=r;c{h.addColorStop(d.i,d.color)}),h}function Lft(s,e){const{x:t,y:i,ex:r,width:n,height:a,center:o}=e.calculative.worldRect;let l=[{x:r,y:i+a/2},{x:t,y:i+a/2}];const{angle:c,colors:u}=qE(e.calculative.textGradientColors);let h=kme(c,n,a);return l.forEach(d=>{Pa(d,c,o)}),vJ(s,l,u,h)}function kme(s,e,t){const i=Math.atan(t/e)/Math.PI*180;let r=(s-90)%360,n=0;return r>i&&r<180-i||r>180+i&&r<360-i||r<0?(r>270?r=360-r:r>180?r=r-180:r>90&&(r=180-r),n=Math.abs(t/Math.sin(r/180*Math.PI)/2)):(r>270?r=360-r:r>180?r=r-180:r>90&&(r=180-r),n=Math.abs(e/Math.cos(r/180*Math.PI)/2)),n}function qE(s){if(typeof s=="string"&&s.startsWith("linear-gradient")){let e=s.slice(16,-2).split("deg,");if(e.length>1){let t=e[1].split("%,");const i=[];return t.forEach(r=>{if(/rgba?/.test(r)){let n=r.split(") ");i.push({color:Oft(n[0]+")"),i:parseFloat(n[1])/100})}else{let n=r.split(" ");n.length>2?i.push({color:n[1],i:parseFloat(n[2])/100}):i.push({color:n[0],i:parseFloat(n[1])/100})}}),{angle:parseFloat(e[0]),colors:i}}else return{angle:parseFloat(e[0]),colors:[]}}else return{angle:0,colors:[]}}function Oft(s){if(/rgba?/.test(s)){let e=s.split(",");if(e.length<3)return"";s="#";for(let t=0,i;i=e[t++];)if(t<4)i=parseInt(i.replace(/[^\d]/gi,""),10).toString(16),s+=i.length==1?"0"+i:i;else{i=i.replace(")","");let n=parseInt(i*255+"").toString(16);n=n.length===2?n:"0"+n,s+=n}s=s.toUpperCase()}return s}function Nft(s,e){const{x:t,y:i,ex:r,width:n,height:a,center:o}=e.calculative.worldRect;let l=[{x:r,y:i+a/2},{x:t,y:i+a/2}];const{angle:c,colors:u}=qE(e.calculative.lineGradientColors);let h=kme(c,n,a);return l.forEach(d=>{Pa(d,c,o)}),vJ(s,l,u,h)}function vJ(s,e,t,i){let r=Ift(e[0].x,e[0].y,e[1].x,e[1].y,i),n=s.createLinearGradient(r[0],r[1],r[2],r[3]);return t.forEach(a=>{n.addColorStop(a.i,a.color)}),n}function _y(s,e,t){let i=[];e.calculative.gradientColorStop?i=e.calculative.gradientColorStop:(i=qE(e.calculative.lineGradientColors).colors,e.calculative.gradientColorStop=i),s.strokeStyle=vJ(s,t,i,e.calculative.lineWidth/2),s.beginPath(),s.moveTo(t[0].x,t[0].y),s.lineTo(t[1].x,t[1].y),s.stroke()}function RNe(s,e){const t=e.calculative.worldAnchors;let i=e.calculative.lineWidth*(e.calculative.gradientSmooth||e.calculative.lineSmooth||0);for(let r=0;r0){let o=t[r-1].curvePoints;o?ZX(s,e,i,o[o.length-1],t[r],t[r].curvePoints[0]):ZX(s,e,i,t[r-1],t[r],t[r].curvePoints[0]);let l=av(i,t[r],t[r].curvePoints[0]);_y(s,e,[l,t[r].curvePoints[1]])}else _y(s,e,[t[r],t[r].curvePoints[0]]),_y(s,e,[t[r].curvePoints[0],t[r].curvePoints[1]]);let n=t[r].curvePoints.length-1;for(let o=1;o0&&r0&&r0&&r0&&r{const w=e.calculative.textLineWidths[T];let P=0;A==="center"?P=(y-w)/2:A==="right"&&(P=y-w),s.fillText(C,g+P,_+(T+x)*b);const{textDecorationColor:M,textDecorationDash:R,textDecoration:I}=e;I&&Gft(s,{x:g+P,y:_+(T+x)*b,width:w},{textDecorationColor:M,textDecorationDash:R,fontSize:r});const{textStrickoutColor:L,textStrickoutDash:k,textStrickout:V}=e;V&&Wft(s,{x:g+P,y:_+(T+x)*b,width:w},{textStrickoutColor:L,textStrickoutDash:k,fontSize:r})}),s.restore()}function Gft(s,e,t){const{textDecorationColor:i,textDecorationDash:r,fontSize:n}=t;let{x:a,y:o,width:l}=e;switch(s.textBaseline){case"top":o+=n;break;case"middle":o+=n/2;break}s.save(),s.beginPath(),s.strokeStyle=i||s.fillStyle,s.lineWidth=1,s.moveTo(a,o),s.setLineDash(r||[]),s.lineTo(a+l,o),s.stroke(),s.restore()}function Wft(s,e,t){const{textStrickoutColor:i,textStrickoutDash:r,fontSize:n}=t;let{x:a,y:o,width:l}=e;switch(s.textBaseline){case"top":o+=n/2;break;case"bottom":o-=n/2;break}s.save(),s.beginPath(),s.strokeStyle=i||s.fillStyle,s.lineWidth=1,s.moveTo(a,o),s.setLineDash(r||[]),s.lineTo(a+l,o),s.stroke(),s.restore()}function wNe(s,e,t){if(t==null)return;const{fontStyle:i,fontWeight:r,fontSize:n,fontFamily:a,lineHeight:o,canvas:l}=e.calculative,c=l.store;s.save();let u;e.calculative.hover?u=e.hoverTextColor||e.hoverColor||c.styles.hoverColor:e.calculative.active&&(u=e.activeTextColor||e.activeColor||c.styles.activeColor),s.fillStyle=u||Ax(e,c),s.font=rp({fontStyle:i,fontWeight:r,fontFamily:a||c.options.fontFamily,fontSize:n,lineHeight:o});const h=s.measureText(t).width;let d,f;for(const p of e.calculative.worldAnchors){if(!f){f=p;continue}const m=_J(f,p),g=Math.floor(m/h);d="";for(let y=0;y0?o=e.calculative.iconSize:i.width>i.height?o=i.height:o=i.width,s.font=rp({fontSize:o,fontWeight:a,fontFamily:l}),s.fillStyle=e.calculative.iconColor||Ax(e,t),e.calculative.iconRotate&&(s.translate(i.center.x,i.center.y),s.rotate(e.calculative.iconRotate*Math.PI/180),s.translate(-i.center.x,-i.center.y)),s.beginPath(),s.fillText(e.calculative.icon,r,n),s.restore()}function LNe(s,e){const t=e.calculative.canvas.store.data.scale,i=e.calculative.canvas.inputDiv.dataset.penId,{x:r,y:n,width:a,height:o}=e.calculative.worldRect;s.save(),s.beginPath(),e.id===i?(s.moveTo(r+a-20*t,n+o/2+2*t),s.lineTo(r+a-14*t,n+o/2-4*t),s.lineTo(r+a-8*t,n+o/2+2*t)):(s.moveTo(r+a-20*t,n+o/2-4*t),s.lineTo(r+a-14*t,n+o/2+2*t),s.lineTo(r+a-8*t,n+o/2-4*t)),s.stroke(),s.restore()}function rp({fontStyle:s="normal",textDecoration:e="normal",fontWeight:t="normal",fontSize:i=12,fontFamily:r="Arial",lineHeight:n=1}={}){return`${s} ${e} ${t} ${i}px/${n} ${r}`}function SS(s,e){const{x:t,ex:i,y:r,ey:n}=e.calculative.worldRect||{};e.calculative.flipX&&(s.translate(t+i+.5,.5),s.scale(-1,1)),e.calculative.flipY&&(s.translate(.5,r+n+.5),s.scale(1,-1))}function vv(s,e,t=!1){const{x:i,y:r}=e.calculative.worldRect.pivot||e.calculative.worldRect.center;s.translate(i,r);let n=e.calculative.rotate*Math.PI/180;t||(e.calculative.flipX&&(n*=-1),e.calculative.flipY&&(n*=-1)),s.rotate(n),s.translate(-i,-r)}function KC(s,e,t){s.save(),s.translate(.5,.5),s.beginPath();const i=e.calculative.canvas.store,r=e.textFlip||i.options.textFlip,n=e.textRotate||i.options.textRotate;(!r||!n)&&s.save(),SS(s,e),e.calculative.rotate&&e.name!=="line"&&vv(s,e),(e.calculative.lineWidth>1||t)&&(s.lineWidth=e.calculative.lineWidth),Jft(s,i,e);let a,o=!1,l;e.calculative.disabled?(l=e.disabledColor||i.styles.disabledColor||Du(.4,e.calculative.color||i.styles.color),a=e.disabledBackground||i.styles.disabledBackground||Du(.4,e.calculative.background||i.styles.penBackground)):e.mouseDownValid&&e.calculative.mouseDown?(l=e.mouseDownColor||Du(-.4,e.calculative.color||i.styles.color),a=e.mouseDownBackground||Du(-.4,e.calculative.background||i.styles.penBackground)):e.switch&&e.calculative.checked?e.calculative.bkType||(a=e.onBackground):e.calculative.hover?(l=e.hoverColor||i.styles.hoverColor,a=e.hoverBackground||i.styles.hoverBackground):e.calculative.active?(l=e.activeColor||i.styles.activeColor,a=e.activeBackground||i.styles.activeBackground):e.calculative.isDock&&(e.type===Kn.Line?l=i.styles.dockPenColor:a=X$(i.styles.dockPenColor,.2));const c=e.calculative.strokeImg;if(e.calculative.strokeImage&&c)s.strokeStyle=l||s.createPattern(c,"repeat");else{let h;e.calculative.strokeType?e.calculative.lineGradientColors?e.name==="line"?o=!0:e.calculative.lineGradient?h=e.calculative.lineGradient:(h=Nft(s,e),e.calculative.lineGradient=h):h=zft(s,e):h=e.calculative.color||(e.type?i.data.lineColor:"")||i.styles.color,s.strokeStyle=l||h}const u=e.calculative.backgroundImg;if(e.calculative.backgroundImage&&u)s.fillStyle=a||s.createPattern(u,"repeat"),a=!0;else{let h;e.calculative.bkType===Pk.Linear?e.calculative.gradientColors?e.calculative.gradient?h=e.calculative.gradient:(h=wft(s,e),e.calculative.gradient=h):h=Mft(s,e):e.calculative.bkType===Pk.Radial?e.calculative.gradientColors?e.calculative.radialGradient?h=e.calculative.radialGradient:(h=Pft(s,e),e.calculative.radialGradient=h):h=Rft(s,e):h=e.calculative.background||i.styles.penBackground,s.fillStyle=a||h,a=!!h}if(ONe(s,e),NNe(s,e),ES(s,e),e.calculative.lineDash&&s.setLineDash(e.calculative.lineDash.map(h=>h*e.calculative.canvas.store.data.scale)),e.calculative.lineDashOffset&&(s.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(s.shadowColor=e.calculative.shadowColor,s.shadowOffsetX=e.calculative.shadowOffsetX,s.shadowOffsetY=e.calculative.shadowOffsetY,s.shadowBlur=e.calculative.shadowBlur),o?(RNe(s,e),BNe(!0,s,e,i)):(FNe(!0,s,e,i,a),KNe(s,e)),!(e.image&&e.calculative.img)&&e.calculative.icon&&DNe(s,e),e.dropdownList&&LNe(s,e),(!r||!n)&&s.restore(),r&&!n&&SS(s,e),!r&&n&&e.calculative.rotate&&e.name!=="line"&&vv(s,e,!0),PNe(s,e),e.type===Kn.Line&&e.fillTexts)for(const h of e.fillTexts)wNe(s,e,h);s.restore()}function ONe(s,e){const t=e.lineCap||(e.type?"round":"square");t?s.lineCap=t:e.type&&(s.lineCap="round")}function NNe(s,e){const t=e.lineJoin;t?s.lineJoin=t:e.type&&(s.lineJoin="round")}function $$(s,e,t,i){var c;s.save(),t&&s.translate(-t.x,-t.y),(c=s.setAttrs)==null||c.call(s,e);let r=!1;const n=e.calculative.canvas.store,a=e.textFlip||n.options.textFlip,o=e.textRotate||n.options.textRotate;s.beginPath(),(!a||!o)&&s.save(),e.calculative.flipX&&(s.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),s.scale(-1,1)),e.calculative.flipY&&(s.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),s.scale(1,-1)),e.calculative.rotate&&e.name!=="line"&&vv(s,e),(e.calculative.lineWidth>1||i)&&(s.lineWidth=e.calculative.lineWidth);let l;if(e.calculative.hover)s.strokeStyle=e.hoverColor||n.styles.hoverColor,s.fillStyle=e.hoverBackground||n.styles.hoverBackground,l=e.hoverBackground||n.styles.hoverBackground;else if(e.calculative.active)s.strokeStyle=e.activeColor||n.styles.activeColor,s.fillStyle=e.activeBackground||n.styles.activeBackground,l=e.activeBackground||n.styles.activeBackground;else{if(e.strokeImage)e.calculative.strokeImg&&(s.strokeStyle=s.createPattern(e.calculative.strokeImg,"repeat"),l=!0);else{let u;e.calculative.strokeType&&e.calculative.lineGradientColors&&e.name==="line"?r=!0:u=e.calculative.color||n.styles.color,s.strokeStyle=u}e.backgroundImage?e.calculative.backgroundImg&&(s.fillStyle=s.createPattern(e.calculative.backgroundImg,"repeat"),l=!0):(s.fillStyle=e.background,l=!!e.background)}if(ONe(s,e),NNe(s,e),ES(s,e),e.calculative.lineDash&&s.setLineDash(e.calculative.lineDash),e.calculative.lineDashOffset&&(s.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(s.shadowColor=e.calculative.shadowColor,s.shadowOffsetX=e.calculative.shadowOffsetX,s.shadowOffsetY=e.calculative.shadowOffsetY,s.shadowBlur=e.calculative.shadowBlur),r?(RNe(s,e),BNe(!0,s,e,n)):(FNe(!1,s,e,n,l),KNe(s,e)),e.calculative.img?(s.save(),s.shadowColor="",s.shadowBlur=0,s.shadowOffsetX=0,s.shadowOffsetY=0,J5(s,e),s.restore()):e.calculative.icon&&DNe(s,e),e.dropdownList&&LNe(s,e),(!a||!o)&&s.restore(),a&&!o&&(e.calculative.flipX&&(s.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),s.scale(-1,1)),e.calculative.flipY&&(s.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),s.scale(1,-1))),!a&&o&&e.calculative.rotate&&e.name!=="line"&&vv(s,e,!0),PNe(s,e),e.type===Kn.Line&&e.fillTexts)for(const u of e.fillTexts)wNe(s,e,u);s.restore()}function FNe(s=!0,e,t,i,r){if(t.name==="drawCommand")return;const n=s?i.path2dMap.get(t):Lr.path2dDraws[t.name];let a=null,o=null;if(t.type===Kn.Line&&(t.fromLineCap&&t.fromLineCap!=="butt"&&(e.lineCap="butt",a=new Path2D,a.moveTo(t.calculative.worldAnchors[0].x,t.calculative.worldAnchors[0].y),a.lineTo(t.calculative.worldAnchors[0].x,t.calculative.worldAnchors[0].y)),t.toLineCap&&t.toLineCap!=="butt"&&(e.lineCap="butt",o=new Path2D,o.moveTo(t.calculative.worldAnchors[t.calculative.worldAnchors.length-1].x,t.calculative.worldAnchors[t.calculative.worldAnchors.length-1].y),o.lineTo(t.calculative.worldAnchors[t.calculative.worldAnchors.length-1].x,t.calculative.worldAnchors[t.calculative.worldAnchors.length-1].y))),n){if(t.type===Kn.Line&&t.borderWidth){e.save(),e.beginPath();const c=t.calculative.lineWidth+t.calculative.borderWidth;e.lineWidth=c,e.strokeStyle=t.borderColor,a&&(e.save(),e.lineCap=t.fromLineCap,e.stroke(a),e.restore()),n instanceof Path2D?(r&&e.fill(n),c&&e.stroke(n)):(n(t,e),r&&e.fill(),c&&e.stroke()),o&&(e.save(),e.lineCap=t.toLineCap,e.stroke(o),e.restore()),e.restore()}n instanceof Path2D?t.type?t.close&&r&&e.fill(n):r&&e.fill(n):(e.save(),n(t,e),r&&e.fill(),e.restore());const l=t.calculative.progress;if(l!=null){e.save();const{ex:c,x:u,y:h,width:d,height:f,ey:p}=t.calculative.worldRect;let m=null;if(t.calculative.verticalProgress?m=t.reverseProgress?e.createLinearGradient(u,h,u,h+f*l):e.createLinearGradient(u,p,u,h+f*(1-l)):m=t.reverseProgress?e.createLinearGradient(c,h,u+d*(1-l),h):e.createLinearGradient(u,h,u+d*l,h),t.calculative.progressGradientColors){const{colors:g}=qE(t.calculative.progressGradientColors);g.forEach(_=>{m.addColorStop(_.i,_.color)})}else{const g=t.calculative.progressColor||t.calculative.color||i.options.activeColor||i.data.color;m.addColorStop(0,g),m.addColorStop(1,g)}m.addColorStop(1,"transparent"),e.fillStyle=m,n instanceof Path2D?e.fill(n):(n(t,e),e.fill()),e.restore()}if(t.calculative.lineWidth&&(n instanceof Path2D?(i.options.svgPathStroke||t.name!=="svgPath")&&(a&&(e.save(),e.lineCap=t.fromLineCap,e.stroke(a),e.restore()),e.stroke(n),o&&(e.save(),e.lineCap=t.toLineCap,e.stroke(o),e.restore())):(n(t,e),e.stroke())),t.type){if(t.calculative.animatePos){if(e.save(),kNe(e,t,i),t.lineAnimateType===u0.Arrow||t.lineAnimateType===u0.WaterDrop){let c=ZNe(t,e);c instanceof Path2D?(e.stroke(c),e.fill(c)):(e.stroke(),e.fill())}else n instanceof Path2D?(a&&!t.lineAnimateType&&(e.save(),e.lineCap=t.fromLineCap,e.stroke(a),e.restore()),e.lineCap=t.lineCap,e.stroke(n)):(n(t,e),e.stroke());e.restore()}t.fromArrow&&ENe(e,t,i),t.toArrow&&TNe(e,t,i),t.calculative.active&&!t.calculative.pencil&&!i.options.disableAnchor&&!i.data.locked&&UNe(e,t)}}}function BNe(s=!0,e,t,i){const r=s?i.path2dMap.get(t):Lr.path2dDraws[t.name];if(r&&t.type){if(t.calculative.animatePos){if(e.save(),kNe(e,t,i),e.beginPath(),r instanceof Path2D)if(t.lineName==="polyline"||t.lineName==="line")if(t.lineAnimateType===u0.Arrow||t.lineAnimateType===u0.WaterDrop){const n=ZNe(t);e.stroke(n),e.fill(n)}else t.calculative.gradientSmooth||t.calculative.lineSmooth?(t.calculative.gradientAnimatePath||(t.calculative.gradientAnimatePath=Ume(t)),t.calculative.gradientAnimatePath instanceof Path2D&&e.stroke(t.calculative.gradientAnimatePath)):e.stroke(r);else e.stroke(r);else r(t,e),e.stroke();e.restore()}t.fromArrow&&ENe(e,t,i),t.toArrow&&TNe(e,t,i),t.calculative.active&&!t.calculative.pencil&&!i.options.disableAnchor&&!i.data.locked&&UNe(e,t)}}function kNe(s,e,t){s.strokeStyle=e.animateColor||t.styles.animateColor,e.animateShadow&&(s.shadowBlur=e.animateShadowBlur||e.animateLineWidth||6,s.shadowColor=e.animateShadowColor||e.animateColor||t.styles.animateColor),e.calculative.animateLineWidth&&(s.lineWidth=e.calculative.animateLineWidth*t.data.scale);let i=0;switch(e.lineAnimateType){case u0.Beads:e.animateReverse?s.lineDashOffset=e.calculative.animatePos:s.lineDashOffset=e.length-e.calculative.animatePos,i=e.calculative.lineWidth||5,i<5&&(i=5);const r=e.animateLineDash&&e.animateLineDash.map(n=>n*i/5);s.setLineDash(r||[i,i*2]);break;case u0.Dot:e.animateReverse?s.lineDashOffset=e.calculative.animatePos:s.lineDashOffset=e.length-e.calculative.animatePos,i=e.calculative.animateDotSize||e.calculative.lineWidth*2||6,i<6&&(i=6),i>40&&(i=40),s.lineWidth=(e.calculative.animateLineWidth||i)*t.data.scale,s.setLineDash([.1,e.length]);break;case u0.Arrow:s.fillStyle=e.animateColor||t.styles.animateColor,s.lineWidth=1;break;case u0.WaterDrop:s.fillStyle=e.animateColor||t.styles.animateColor,s.lineWidth=1;break;default:e.animateReverse?(s.lineDashOffset=Number.EPSILON,s.setLineDash([0,e.length-e.calculative.animatePos+1,e.calculative.animatePos])):s.setLineDash([e.calculative.animatePos,e.length+.01-e.calculative.animatePos]);break}}function UNe(s,e){const t=e.calculative.canvas.store;s.save(),s.lineWidth=1,s.fillStyle=e.activeColor||t.styles.activeColor,e.calculative.worldAnchors.forEach(i=>{!i.hidden&&!i.isTemp&&Kft(s,i,e)}),s.restore()}function Kft(s,e,t){if(!e)return;const i=t.calculative.canvas.store.activeAnchor===t.calculative.activeAnchor&&t.calculative.activeAnchor===e;let r=3;t.calculative.lineWidth>3&&(r=t.calculative.lineWidth),t.anchorRadius&&(r=t.anchorRadius),e.radius&&(r=e.radius),i?(e.prev&&(s.save(),s.strokeStyle="#4dffff",s.beginPath(),s.moveTo(e.prev.x,e.prev.y),s.lineTo(e.x,e.y),s.stroke(),s.restore(),s.save(),s.fillStyle="#ffffff",s.beginPath(),s.arc(e.prev.x,e.prev.y,r,0,Math.PI*2),s.fill(),s.stroke(),s.restore()),e.next&&(s.save(),s.strokeStyle="#4dffff",s.beginPath(),s.moveTo(e.x,e.y),s.lineTo(e.next.x,e.next.y),s.stroke(),s.restore(),s.save(),s.fillStyle="#ffffff",s.beginPath(),s.arc(e.next.x,e.next.y,r,0,Math.PI*2),s.fill(),s.stroke(),s.restore(),s.beginPath(),s.arc(e.x,e.y,r,0,Math.PI*2),s.fill(),s.stroke()),s.beginPath(),s.arc(e.x,e.y,r,0,Math.PI*2),s.fill(),s.stroke()):(s.save(),s.fillStyle="#ffffff",s.beginPath(),s.arc(e.x,e.y,r,0,Math.PI*2),s.fill(),s.stroke(),s.restore())}function zNe(s){const e=s.calculative.canvas.store;let t={x:s.x,y:s.y};if(!s.parentId||s.parentId&&!e.pens[s.parentId])s.parentId=void 0,t.width=s.width,t.height=s.height,t.rotate=s.rotate,Go(t),ro(t),s.pivot&&eue(t,s.pivot);else{const i=e.pens[s.parentId];let r=i.calculative.worldRect;r||(r=zNe(i)),t.x=r.x+r.width*s.x,t.y=r.y+r.height*s.y,t.width=r.width*s.width,t.height=r.height*s.height,i.flipX&&(t.x=r.width-(t.x-r.x+t.width)+r.x),i.flipY&&(t.y=r.height-(t.y-r.y+t.height)+r.y),Go(t),t.rotate=r.rotate+s.rotate,ro(t),s.pivot&&eue(t,s.pivot)}return s.calculative.worldRect=t,zme(s,t),t}function zme(s,e){!s.paddingTop&&(s.calculative.paddingTop=0),!s.paddingBottom&&(s.calculative.paddingBottom=0),!s.paddingLeft&&(s.calculative.paddingLeft=0),!s.paddingRight&&(s.calculative.paddingRight=0),Math.abs(s.calculative.paddingTop)<1&&(s.calculative.paddingTop*=e.height),Math.abs(s.calculative.paddingBottom)<1&&(s.calculative.paddingBottom*=e.height),Math.abs(s.calculative.paddingLeft)<1&&(s.calculative.paddingLeft*=e.width),Math.abs(s.calculative.paddingRight)<1&&(s.calculative.paddingRight*=e.width)}function GQ(s){const e=bt(s.calculative.worldRect);if(delete e.pivot,!s.parentId){Object.assign(s,e);return}const i=s.calculative.canvas.store.pens[s.parentId].calculative.worldRect;Object.assign(s,yy(e,i))}function eP(s){const e=s.calculative.canvas.store;let t=[];if(s.anchors){let i=bt(s.anchors);s.flipX&&i.forEach(r=>{r.x=.5-(r.x-.5)}),s.flipY&&i.forEach(r=>{r.y=.5-(r.y-.5)}),i.forEach(r=>{t.push(Hft(s,r))})}if(!t.length&&!s.type&&!s.calculative.canvas.parent.isCombine(s)){const{x:i,y:r,width:n,height:a}=s.calculative.worldRect;t=e.options.defaultAnchors.map((o,l)=>({id:`${l}`,penId:s.id,x:i+n*o.x,y:r+a*o.y}))}s.calculative.rotate&&t.forEach(i=>{Pa(i,s.calculative.rotate,s.calculative.worldRect.pivot||s.calculative.worldRect.center)}),(!s.type||s.anchors)&&(s.calculative.worldAnchors=t),s.calculative.activeAnchor&&t.length&&(s.calculative.activeAnchor=t.find(i=>{i.id,s.calculative.activeAnchor.id})),s.calculative.gradientAnimatePath=void 0}function VNe(s){var e;if((e=s.children)!=null&&e.length){let t=s.calculative.worldRect;s.children.forEach(i=>{const r=s.calculative.canvas.store.pens[i];r.calculative.initRect&&r.calculative.initRelativeRect&&(r.calculative.initRect.x=t.x+t.width*r.calculative.initRelativeRect.x,r.calculative.initRect.y=t.y+t.height*r.calculative.initRelativeRect.y,r.calculative.initRect.ex=r.calculative.initRect.x+t.width*r.calculative.initRelativeRect.width,r.calculative.initRect.ey=r.calculative.initRect.y+t.height+r.calculative.initRelativeRect.height,ro(r.calculative.initRect)),VNe(r)})}}function Hft(s,e){const t={...e},{x:i,y:r,width:n,height:a}=s.calculative.worldRect;return t.x=i+n*e.x,t.y=r+a*e.y,e.prev&&(t.prev={penId:s.id,connectTo:e.prev.connectTo,x:i+n*e.prev.x,y:r+a*e.prev.y}),e.next&&(t.next={penId:s.id,connectTo:e.next.connectTo,x:i+n*e.next.x,y:r+a*e.next.y}),t}function J6e(s,e){const{paddingTop:t,paddingBottom:i,paddingLeft:r,paddingRight:n}=e.calculative;let a=r,o=t,l=e.calculative.worldRect.width-r-n,c=e.calculative.worldRect.height-t-i,u=e.calculative.iconLeft,h=e.calculative.iconTop;u&&Math.abs(u)<1&&(u=e.calculative.worldRect.width*u),h&&Math.abs(h)<1&&(h=e.calculative.worldRect.height*h),a+=u||0,o+=h||0,l-=u||0,c-=h||0;let d=e.calculative.iconRotate||0;if(e.parentId){const f=s[e.parentId].calculative;f&&(d+=f.rotate,d%=360)}a=e.calculative.worldRect.x+a,o=e.calculative.worldRect.y+o,e.calculative.worldIconRect={x:a,y:o,width:l,height:c,rotate:d},Go(e.calculative.worldIconRect),ro(e.calculative.worldIconRect)}function wI(s,e,t){wk(s.calculative.worldRect,e,t,s.pivot),s.calculative.initRect&&wk(s.calculative.initRect,e,t,s.pivot),GNe(s,e,t),s.calculative.x&&j$(s.calculative,e,t),s.type&&eP(s)}function GNe(s,e,t){var i;s&&(i=s.children)!=null&&i.length&&s.children.forEach(r=>{const n=s.calculative.canvas.store.pens[r];n&&(n.calculative.initRect&&wk(n.calculative.initRect,e,t),GNe(n,e,t))})}function jft(s,e){s.anchors||(s.anchors=[]),s.calculative.worldAnchors||(s.calculative.worldAnchors=[]);const t={id:e.id,penId:s.id,x:e.x,y:e.y};if(s.calculative.worldAnchors.push(t),s.calculative.worldRect){s.rotate%360&&Pa(e,-s.rotate,s.calculative.worldRect.center);const i={id:e.id,penId:s.id,x:(e.x-s.calculative.worldRect.x)/s.calculative.worldRect.width,y:(e.y-s.calculative.worldRect.y)/s.calculative.worldRect.height};s.anchors.push(i)}return t}function Xft(s,e,t){s.anchors||(s.anchors=[]),s.calculative.worldAnchors||(s.calculative.worldAnchors=[]);const i=Kpt(s,e,t);return s.calculative.worldAnchors.splice(t+1,0,i),s.anchors.splice(t+1,0,kB(i,s.calculative.worldRect)),s.calculative.activeAnchor=i,i}function Yft(s,e){if(!s||!s.calculative.worldAnchors)return;let t=s.calculative.worldAnchors.findIndex(i=>i.id===e.id);t>-1&&s.calculative.worldAnchors.splice(t,1),t=s.anchors.findIndex(i=>i.id===e.id),t>-1&&s.anchors.splice(t,1)}function $P(s,e){if(!e||!e.calculative||!e.calculative.worldRect.center)return Ts.None;if(s.anchorId){let t=e.anchors.filter(i=>i.id===s.anchorId);if(t.length&&t[0].direction>-1)return t[0].direction}return Ydt(s,e.calculative.worldRect.center)}function R5(s,e){let t=1/0,i;return s.calculative.worldAnchors.forEach(r=>{const n=_J(e,r);t>n&&(t=n,i=r)}),i}function eEe(s,e,t){s.x+=e,s.y+=t,s.anchors&&s.anchors.forEach(i=>{BB(i,e,t)}),s.calculative.worldAnchors&&s.calculative.worldAnchors.forEach(i=>{BB(i,e,t)})}function Vme(s){if(s&&s.calculative&&s.calculative.worldAnchors.length){let e=Dn(s);if(!s.anchors||!s.anchors.length)for(;s.calculative.worldAnchors.length&&e!==s.calculative.activeAnchor;)s.calculative.worldAnchors.pop(),e=Dn(s);else e===s.calculative.activeAnchor?s.calculative.worldAnchors=[s.calculative.worldAnchors[0]]:s.calculative.worldAnchors[0]===s.calculative.activeAnchor&&(s.calculative.worldAnchors=[s.calculative.worldAnchors[s.calculative.worldAnchors.length-1]])}}function Zc(s,e,t,i){var o,l,c,u,h,d;if(!s||!e||!t||!i||e.twoWay===uh.DisableConnected||e.twoWay===uh.Disable||i.twoWay===uh.DisableConnectTo||i.twoWay===uh.Disable)return;if(e.twoWay===uh.In){if(t.calculative.worldAnchors.length===1)return;const f=Dn(t);if(i.id!==f.id)return}if(e.twoWay===uh.Out){const f=rl(t);if(i.id!==f.id)return}if(i.connectTo===s.id&&i.anchorId===e.id)return;if(i.connectTo){const f=s.calculative.canvas.store.pens[i.connectTo];I5(f,HC(f,i.anchorId),t,i)}s.connectedLines||(s.connectedLines=[]),s.connectedLines.findIndex(f=>f.lineId===t.id&&f.lineAnchor===i.id&&f.anchor===e.id)<0&&s.connectedLines.push({lineId:t.id,lineAnchor:i.id,anchor:e.id}),i.connectTo=s.id,i.anchorId=e.id,s.type&&Zc(t,i,s,e),s.calculative.canvas.store.emitter.emit("connectLine",{line:t,lineAnchor:i,pen:s,anchor:e});let n=((o=t.calculative.worldAnchors)==null?void 0:o.length)>=2?(l=t.calculative.worldAnchors)==null?void 0:l[0].connectTo:void 0,a=((c=t.calculative.worldAnchors)==null?void 0:c.length)>=2?(h=t.calculative.canvas.store.pens[(u=t.calculative.worldAnchors)==null?void 0:u[0].connectTo])==null?void 0:h.anchors.find(f=>{var p;return f.id===((p=t.calculative.worldAnchors)==null?void 0:p[0].anchorId)}):void 0;return(d=s.onConnectLine)==null||d.call(s,s,{line:t,lineAnchor:i,pen:s,anchor:e,fromPen:n,fromAnchor:a}),!0}function I5(s,e,t,i){if(!(!s||!e||!t||!i)&&!(!s.connectedLines||!s.connectedLines.length))return t.lastConnected||(t.lastConnected={}),t.lastConnected[s.id]||(t.lastConnected[s.id]=bt(s.connectedLines)),s.connectedLines.forEach((r,n,a)=>{(r.lineId===t.id||r.lineId===t.id)&&r.lineAnchor===i.id&&r.anchor===e.id&&a.splice(n,1)}),i.connectTo=void 0,i.anchorId=void 0,s.type&&e.connectTo===t.id&&e.anchorId===i.id&&I5(t,i,s,e),s.calculative.canvas.store.emitter.emit("disconnectLine",{line:t,lineAnchor:i,pen:s,anchor:e}),!0}function HC(s,e){var t;if(!(!s||!e))return(t=s.calculative.worldAnchors)==null?void 0:t.find(i=>i.id===e)}function rl(s){if(!(!s||!s.calculative.worldAnchors))return s.calculative.worldAnchors[0]}function Dn(s){if(!(!s||!s.calculative.worldAnchors))return s.calculative.worldAnchors[s.calculative.worldAnchors.length-1]}function Qft(s,e){var i,r;if(s.calculative.start===0||!s.frames||!s.frames.length)return s.calculative.start=void 0,0;if(!s.calculative.duration){s.calculative.duration=0;for(const n of s.frames){s.calculative.duration+=n.duration;for(const a in n)a!=="duration"&&!s[a]&&a==="scale"&&(s[a]=1)}}if(s.animateCycle||(s.animateCycle=1/0),s.calculative.start){let n=0;const a=Math.ceil((e-s.calculative.start)/s.calculative.duration);if(a>s.animateCycle)return s.currentAnimation=void 0,s.calculative.start=void 0,iEe(s,1),0;const o=(e-s.calculative.start)%s.calculative.duration||s.calculative.duration;let l=0;for(const h of s.frames)if(l+=h.duration,o>l)++n;else break;if(!s.frames[n])return!0;let c=!1;n!==s.calculative.frameIndex&&(c=!0,s.calculative.frameIndex=n,s.calculative.frameDuration=s.frames[n].duration,n>0&&(s.calculative.frameStart+=s.frames[n-1].duration),s.calculative.frameEnd=s.calculative.frameStart+s.calculative.frameDuration);let u=!1;if(a>s.calculative.cycleIndex&&(s.calculative.cycleIndex=a,s.calculative.frameStart=s.calculative.start+s.calculative.duration*(a-1),u=!0),c||u)if(s.calculative.x=s.calculative.initRect.x,s.calculative.y=s.calculative.initRect.y,(r=s.children)!=null&&r.length&&!s.parentId?s.calculative.canvas.rotatePen(s,(s.calculative.initRect.rotate||0)-(s.calculative.rotate||0),s.calculative.initRect):s.calculative.rotate=s.calculative.initRect.rotate||0,n>0){s.prevFrame={};const h=s.frames[n-1];for(const d in h)s.prevFrame[d]=h[d];Object.assign(s.prevFrame,{rotate:h.rotate||0,x:h.x||0,y:h.y||0,scale:h.scale||1})}else tEe(s)}else{if(s.calculative.start=e,s.calculative.frameIndex=0,s.calculative.frameStart=s.calculative.start,s.calculative.frameDuration=s.frames[0].duration,s.calculative.frameEnd=s.calculative.frameStart+s.calculative.frameDuration,s.calculative.cycleIndex=1,s.calculative.x=s.calculative.worldRect.x,s.calculative.y=s.calculative.worldRect.y,s.calculative.initRect=bt(s.calculative.worldRect),s.parentId&&(s.calculative.initRelativeRect={x:s.x,y:s.y,width:s.width,height:s.height}),(i=s.children)!=null&&i.length){const n=s.calculative.canvas.store;s.calculative.childrenVisible={},s.children.forEach(a=>{s.calculative.childrenVisible[a]=n.pens[a].visible})}s.calculative.initRect.rotate=s.calculative.rotate||0,tEe(s)}const t=(e-s.calculative.frameStart)/s.calculative.frameDuration%1;return t>0&&iEe(s,t),!0}function tEe(s){s.prevFrame={};for(const e in s)(typeof s[e]!="object"||e==="lineDash")&&(s.prevFrame[e]=s[e]);s.prevFrame.rotate=0,s.prevFrame.x=0,s.prevFrame.y=0,s.prevFrame.scale=1}function iEe(s,e){var r,n,a,o,l,c;if(e<0)return;e>1&&(e=1);const t=s.frames[s.calculative.frameIndex],i=s.calculative.canvas.store.data.scale;for(const u in t)if(u!=="duration"){if(u==="scale"){s.calculative.worldRect=bt(s.calculative.initRect),wk(s.calculative.worldRect,s.prevFrame.scale,s.calculative.worldRect.center);const h=s.prevFrame.scale+(t[u]-s.prevFrame.scale)*e;wk(s.calculative.worldRect,h/s.prevFrame.scale,s.calculative.worldRect.center),s.calculative.patchFlags=!0}else if(u==="x"){const h=v9(s,u,s.calculative.frameIndex)*i;s.calculative.worldRect.x=s.calculative.initRect.x+h,s.calculative.worldRect.ex=s.calculative.initRect.ex+h,s.calculative.worldRect.center.x=s.calculative.initRect.center.x+h,(r=s.calculative.worldRect.pivot)!=null&&r.x&&(s.calculative.worldRect.pivot.x=((n=s.calculative.initRect.pivot)==null?void 0:n.x)+h),lS(s.calculative.worldRect,t[u]*e*i,0),s.calculative.patchFlags=!0}else if(u==="y"){const h=v9(s,u,s.calculative.frameIndex)*i;s.calculative.worldRect.y=s.calculative.initRect.y+h,s.calculative.worldRect.ey=s.calculative.initRect.ey+h,s.calculative.worldRect.center.y=s.calculative.initRect.center.y+h,(a=s.calculative.worldRect.pivot)!=null&&a.x&&(s.calculative.worldRect.pivot.y=((o=s.calculative.initRect.pivot)==null?void 0:o.y)+h),lS(s.calculative.worldRect,0,t[u]*e*i),s.calculative.patchFlags=!0}else if(u==="width"){const h=v9(s,u,s.calculative.frameIndex)*i;s.calculative.worldRect.width=s.calculative.initRect.width+h,s.calculative.worldRect.ex=s.calculative.initRect.ex+h,s.calculative.worldRect.center.x=s.calculative.initRect.center.x+h;let d=t[u]*e*i;s.calculative.worldRect.width+=d,s.calculative.worldRect.ex+=d,s.calculative.worldRect.center.x+=d,s.calculative.patchFlags=!0}else if(u==="height"){const h=v9(s,u,s.calculative.frameIndex)*i;s.calculative.worldRect.height=s.calculative.initRect.height+h,s.calculative.worldRect.ey=s.calculative.initRect.ey+h,s.calculative.worldRect.center.y=s.calculative.initRect.center.y+h;let d=t[u]*e*i;s.calculative.worldRect.height+=d,s.calculative.worldRect.ey+=d,s.calculative.worldRect.center.y+=d,s.calculative.patchFlags=!0}else if(u==="rotate"){s.prevFrame[u]>=360&&(s.prevFrame[u]%=360);const h=v9(s,u,s.calculative.frameIndex),d=(s.calculative.initRect.rotate+h+t[u]*e)%360-(s.calculative.rotate||0);(l=s.children)!=null&&l.length?s.calculative.canvas.rotatePen(s,d,s.calculative.initRect):s.calculative.rotate=(s.calculative.initRect.rotate+h+t[u]*e)%360,s.calculative.patchFlags=!0}else if(u==="image")s.image=t.image,s.calculative.image=void 0,s.calculative.canvas.loadImage(s),s.canvasLayer===hn.CanvasImageBottom?s.calculative.canvas.canvasImageBottom.init():s.canvasLayer===hn.CanvasImage&&s.calculative.canvas.canvasImage.init();else if($ft(t[u],u,s)){s.prevFrame[u]==null&&(u==="globalAlpha"?s.prevFrame[u]=1:s.prevFrame[u]=0);const h=s.prevFrame[u]+(t[u]-s.prevFrame[u])*e;s.calculative[u]=Math.round(h*100)/100}else{if(u==="visible"&&!s.calculative.image){if((c=s.children)!=null&&c.length){const d=S1(s,s.calculative.canvas.store);s.calculative.canvas.initImageCanvas(d)}}s.calculative[u]=t[u];const h={};h[u]=t[u],Gme(s,h)}u==="text"&&iz(s)}}function $ft(s,e,t){const i=["strokeType","bkType","showChild"];return typeof s=="number"&&t.linear!==!1&&!i.includes(e)}function Zft(s,e){if(s.calculative.start===0)return s.calculative.start=void 0,0;if(s.animateCycle||(s.animateCycle=1/0),s.animateSpan||(s.animateSpan=1),s.calculative.animatePos+=s.animateSpan*(s.calculative.canvas.store.data.scale||1),!s.calculative.start)s.calculative.start=Date.now(),s.calculative.animatePos=s.animateSpan*(s.calculative.canvas.store.data.scale||1),s.calculative.cycleIndex=1;else if(s.calculative.animatePos>s.length){if(++s.calculative.cycleIndex,s.calculative.cycleIndex>s.animateCycle)return s.currentAnimation=void 0,s.calculative.start=void 0,0;s.calculative.animatePos=s.animateSpan}return!0}function v5(s,e=!0){if(!s.children||s.childActive===!1)return;const t=s.calculative.canvas.store;s.children.forEach(i=>{const r=t.pens[i];r&&(r.calculative.active=e,v5(r,e))})}function pB(s,e=!0){if(!s)return;const t=s.calculative.canvas.store;s.calculative.hover=e,s.childHover!==!1&&s.children&&s.children.forEach(i=>{var r,n;((r=t.pens[i])==null?void 0:r.hoverColor)==null&&((n=t.pens[i])==null?void 0:n.hoverBackground)==null&&pB(t.pens[i],e)})}function Ha(s,e){if(!e)return;const t=s.calculative.canvas.store,i=s.calculative.worldRect;e.style.opacity=s.globalAlpha+"",e.style.position="absolute",e.style.outline="none",e.style.left=i.x+t.data.x+"px",e.style.top=i.y+t.data.y+"px",e.style.width=i.width+"px",e.style.height=i.height+"px",e.style.display=s.calculative.inView!=!1?s.calculative.cssDisplay||"inline":"none",!s.calculative.rotate&&(s.calculative.rotate=0),e.style.transform=`rotate(${s.calculative.rotate}deg)`,s.calculative.rotate||(s.calculative.flipX&&(e.style.transform="rotateY(180deg)"),s.calculative.flipY&&(e.style.transform="rotateX(180deg)"),s.calculative.flipX&&s.calculative.flipY&&(e.style.transform="rotateZ(180deg)")),e.style.zIndex=s.calculative.zIndex!==void 0?s.calculative.zIndex+"":"5",s.calculative.zIndex>s.calculative.canvas.maxZindex&&(s.calculative.canvas.maxZindex=s.calculative.zIndex),s.locked===qs.DisableEdit||s.locked===qs.DisableMove||t.data.locked?(e.style.userSelect="initial",e.style.pointerEvents="initial",s.name==="gif"&&(e.style.userSelect="none",e.style.pointerEvents="none")):(e.style.userSelect="none",e.style.pointerEvents="none")}function Ose(s){return s.every(e=>e.locked)}function rEe(s){return s.every(e=>e.disableRotate)}function WNe(s,e,t){var i;s.type?(s.calculative.worldAnchors.forEach(r=>{Pa(r,e,t.center)}),qft(s),GQ(s)):(s.calculative.rotate?s.calculative.rotate+=e:s.calculative.rotate=e,Pa(s.calculative.worldRect.center,e,t.center),s.parentId&&(s.calculative.worldRect.x=s.calculative.worldRect.center.x-s.calculative.worldRect.width/2,s.calculative.worldRect.y=s.calculative.worldRect.center.y-s.calculative.worldRect.height/2,s.x=(s.calculative.worldRect.x-t.x)/t.width,s.y=(s.calculative.worldRect.y-t.y)/t.height)),(i=s.children)==null||i.forEach(r=>{const n=s.calculative.canvas.store.pens[r];WNe(n,e,t)})}function qft(s){var r;if(!((r=s.calculative.worldAnchors)!=null&&r.length)||!isFinite(s.x)||!isFinite(s.x)||s.x==null||s.y==null)return;const e=rue(s);s.parentId||Object.assign(s,e);const{fontSize:t,lineHeight:i}=s.calculative.canvas.store.options;s.fontSize?s.fontSize<0&&(s.fontSize=0,s.calculative.fontSize=0):(s.fontSize=t>=0?t:12,s.calculative.fontSize=s.fontSize*s.calculative.canvas.store.data.scale),s.lineHeight||(s.lineHeight=i,s.calculative.lineHeight=s.lineHeight),ro(e),s.calculative.worldRect=e,zme(s,e),L1(s),s.calculative.worldAnchors&&(s.anchors=s.calculative.worldAnchors.map(n=>kB(n,s.calculative.worldRect)))}function sEe(s){return s.every(e=>e.disableSize||e.pivot)}function v9(s,e,t){if(!s.frames||!e)return 0;let i=0;for(let r=0;r{const l=t.pens[o];l&&sv(l,!0)})),s.calculative.inView=!0,Z$(s,t)?(s.visible==!1||s.calculative.visible==!1)&&(s.calculative.inView=!1,(s.canvasLayer===hn.CanvasImageBottom||s.canvasLayer===hn.CanvasImage)&&((n=s.frames)!=null&&n.length)&&(s.calculative.inView=s.frames.some(o=>o.hasOwnProperty("visible")))):s.calculative.inView=!1,s.calculative.inView){const{x:o,y:l,width:c,height:u,rotate:h}=s.calculative.worldRect,d={x:o+t.data.x,y:l+t.data.y,width:c,height:u,rotate:h};Go(d),ov(d,i)||(s.calculative.inView=!1)}(a=s.calculative.singleton)!=null&&a.div&&Ha(s,s.calculative.singleton.div)}function Jft(s,e,t){if(e.fillWorldTextRect){s.save(),s.fillStyle="#c3deb7";const{x:i,y:r,width:n,height:a}=t.calculative.worldTextRect;s.fillRect(i,r,n,a),s.restore()}}function ES(s,e){const t=e.calculative.globalAlpha;typeof t=="number"&&t<1&&!isNaN(t)&&(s.globalAlpha=t)}function KNe(s,e){const t=ept(s,e)||Lr.canvasDraws[e.name];t&&(s.save(),t(s,e),s.restore())}function ept(s,e){const t=e.drawCommand;if(!(!t||e.name==="line"))return(i,r)=>{t.forEach(n=>{try{n.steps=n.steps.flat(1/0),n.steps.reduce((a,o)=>{const l=tpt(o,r,a.x,a.y);try{if(l.c){if(l.c.startsWith("_")){const u=l.c.split("_")[1];return typeof l.v.value=="number"&&(l.v.value*=r.calculative.canvas.store.data.scale),(l.p||i)[u]=l.v.value,{x:a.x,y:a.y}}let c=[];for(const u in l.v)c.push(l.v[u]);return(l.p||i)[l.c](...c),{x:l.startX||l.v.x,y:l.startY||l.v.y}}return{x:a.x,y:a.y}}catch{}},{})}catch{}}),i.stroke()}}function tpt(s,e,t,i){var n;const r={visio:spt,dxf:ipt,canvas:rpt};return((n=r[e.parseType])==null?void 0:n.call(r,s,e,t,i))||s}function ipt(s,e,t,i){const{x:r,y:n,width:a,height:o}=e.calculative.worldRect,{originWidth:l,originHeight:c}=e.dxfOrigin;switch(s.c){case"beginPath":return{c:"beginPath",v:{}};case"closePath":return{c:"closePath",v:{}};case"moveTo":return{c:"moveTo",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n}};case"lineTo":return{c:"lineTo",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n}};case"arc":return{c:"ellipse",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n,rx:s.v.xr*(a/l),ry:s.v.yr*(o/c),rotation:s.v.rotation||0,startAngle:s.v.startAngle,endAngle:s.v.endAngle,a:s.v.aclockwise??!0}};case"ellipse":return{c:"ellipse",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n,rx:s.v.xr*(a/l),ry:s.v.yr*(o/c),rotation:s.v.rotation||0,startAngle:s.v.startAngle,endAngle:s.v.endAngle,a:s.v.aclockwise??!0}};case"_font":return{c:"_font",v:{value:s.v.fontSize*e.calculative.canvas.store.data.scale+"px "+(s.v.fontFamily||e.calculative.canvas.store.options.fontFamily)}};case"_fillStyle":return{c:"_fillStyle",v:{value:e.color||s.v.value}};default:const u={c:s.c,v:{...s.v}};return u.v.x!==void 0&&(u.v.x=s.v.x*(a/l)+r),u.v.y!==void 0&&(u.v.y=s.v.y*(o/c)+n),u}}function rpt(s,e,t,i){const{x:r,y:n,width:a,height:o}=e.calculative.worldRect,{originWidth:l,originHeight:c}=e.origin;switch(s.c){case"beginPath":return{c:"beginPath",v:{}};case"closePath":return{c:"closePath",v:{}};case"moveTo":return{c:"moveTo",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n}};case"lineTo":return{c:"lineTo",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n}};case"arc":return{c:"ellipse",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n,rx:s.v.xr*(a/l),ry:s.v.yr*(o/c),rotation:s.v.rotation||0,startAngle:s.v.startAngle,endAngle:s.v.endAngle,a:s.v.aclockwise??!0}};case"ellipse":return{c:"ellipse",v:{x:s.v.x*(a/l)+r,y:s.v.y*(o/c)+n,rx:s.v.xr*(a/l),ry:s.v.yr*(o/c),rotation:s.v.rotation||0,startAngle:s.v.startAngle,endAngle:s.v.endAngle,a:s.v.aclockwise??!0}};case"_font":return{c:"_font",v:{value:s.v.fontSize*e.calculative.canvas.store.data.scale+"px "+(s.v.fontFamily||e.calculative.canvas.store.options.fontFamily)}};default:const u={c:s.c,v:{...s.v}};return u.v.x!==void 0&&(u.v.x=s.v.x*(a/l)+r),u.v.y!==void 0&&(u.v.y=s.v.y*(o/c)+n),u}}function spt(s,e,t,i){const{x:r,y:n,width:a,height:o}=e.calculative.worldRect,{width:l,height:c}=e.origin;switch(s.c){case"MoveTo":return{c:"moveTo",v:{x:+s.v.X*100*(a/l)+r,y:+s.v.Y*100*(o/c)+n}};case"RelMoveTo":return{c:"moveTo",v:{x:+s.v.X*l*(a/l)+r,y:+s.v.Y*c*(o/c)+n}};case"LineTo":return{c:"lineTo",v:{x:+s.v.X*100*(a/l)+r,y:+s.v.Y*100*(o/c)+n}};case"RelLineTo":return{c:"lineTo",v:{x:+s.v.X*l*(a/l)+r,y:+s.v.Y*c*(o/c)+n}};case"Ellipse":let u=s.v.X,h=s.v.Y,d=Math.abs(s.v.A-s.v.C),f=Math.abs(s.v.B-s.v.D);return{c:"ellipse",v:{x:u*100*(a/l)+r,y:h*100*(o/c)+n,radiuX:d*100*(a/l),radiuY:f*100*(o/c),rotation:0,startAngle:0,endAngle:Math.PI*2,anticlockwise:!0}};case"EllipticalArcTo":const p=s.v.X*100*(a/l)+r,m=s.v.Y*100*(o/c)+n,g=s.v.A*100*(a/l)+r,_=s.v.B*100*(o/c)+n;s.v.C;const y=s.v.D*(a/o)*(c/l),v=(p-t)*(_-i)-(m-i)*(g-t)>0,x=nEe(t,i,p,m,g,_,y);return!s.orign&&(s.orign={}),!s.orign.startA&&(s.orign.startA=qX(x.x0,x.y0,t,i)),!s.orign.endA&&(s.orign.endA=qX(x.x0,x.y0,p,m)),{c:"ellipse",v:{centerX:x.x0,centerY:x.y0,radiuX:x.a,radiuY:x.b,rotation:0,startAngle:s.orign.startA,endAngle:s.orign.endA,anticlockwise:v},startX:p,startY:m};case"RelEllipticalArcTo":const A=s.v.X*l*(a/l)+r,b=s.v.Y*c*(o/c)+n,C=s.v.A*l*(a/l)+r,T=s.v.B*c*(o/c)+n;s.v.C;const w=s.v.D*(a/o)*(c/l),P=(A-t)*(T-i)-(b-i)*(C-t)>0,M=nEe(t,i,A,b,C,T,w);return!s.orign&&(s.orign={}),!s.orign.startA&&(s.orign.startA=qX(M.x0,M.y0,t,i)),!s.orign.endA&&(s.orign.endA=qX(M.x0,M.y0,A,b)),{c:"ellipse",v:{centerX:M.x0,centerY:M.y0,radiuX:M.a,radiuY:M.b,rotation:0,startAngle:s.orign.startA,endAngle:s.orign.endA,anticlockwise:P},startX:A,startY:b};case"ArcTo":let R=s.v.X*100*a/l+r,I=s.v.Y*100*o/c+n,L=s.v.A*100*(a/o)*(c/l),k=(t+R)/2,V=(i+I)/2,H=Math.sqrt((R-t)**2+(I-i)**2),j=H**2/(8*L)+L/2,z=-(I-i)/H,K=(R-t)/H,U=k+z*j,W=V+K*j,Z=U,q=W,ie=Math.atan2(i-q,t-Z),ae=Math.atan2(I-q,R-Z);return{c:"arc",v:{x:Z,y:q,radius:j,startAngle:ie,endAngle:ae,aclockwise:!0}};default:const ue=bt(s);return Object.entries(ue.v).forEach(([ce,N])=>{var B,Y;(B=ce.endsWith)!=null&&B.call(ce,"_x")?typeof N=="number"&&(ue.v[ce]=N*(a/l)+r):(Y=ce.endsWith)!=null&&Y.call(ce,"_y")?typeof N=="number"&&(ue.v[ce]=N*(o/c)+n):typeof N=="number"&&(ue.v[ce]=N)}),ue}}function Gme(s,e){for(const t in e)ANe.includes(t)&&(t=="fontSize"&&e[t]<0&&(e[t]=0),s[t]=e[t],["fontSize","lineWidth"].includes(t)?(s.calculative[t]=e[t]*s.calculative.canvas.store.data.scale,L1(s)):s.calculative[t]=e[t]);if(s.calculative.canvas.parent.isCombine(s)){const t=s.children;t==null||t.forEach(i=>{let r=bt(e);s.calculative.childrenVisible&&s.calculative.childrenVisible[i]===!1&&delete r.visible;const n=s.calculative.canvas.store.pens[i];n&&Gme(n,r)})}}function nEe(s,e,t,i,r,n,a){let o=(s-t)*(s+t)*(i-n)-(t-r)*(t+r)*(e-i)+a*a*(e-i)*(i-n)*(e-n),l=2*((s-t)*(i-n)-(t-r)*(e-i)),c=o/l,u=(s-t)*(t-r)*(s-r)+a*a*((t-r)*(e-i)*(e+i)-(s-t)*(i-n)*(i+n)),h=2*a*a*((t-r)*(e-i)-(s-t)*(i-n)),d=u/h,f=Math.sqrt(Math.pow(s-c,2)+Math.pow(a*(e-d),2)),p=f/a;return{x0:c,y0:d,a:f,b:p}}function qX(s,e,t,i){let r=t-s,n=i-e,a=Math.atan2(n,r);return a<0&&(a+=2*Math.PI),a}function aEe(s,e,t){let i,r,n=1/0,a=1/0;const o=8;for(const l of s.data.pens){if(l.calculative.inView===!1)continue;Wme(l).forEach(u=>{if(u===e||u===t)return;let h=(l.calculative.worldRect.center.x-e.x)*(l.calculative.worldRect.center.x-e.x)+(l.calculative.worldRect.center.y-e.y)*(l.calculative.worldRect.center.y-e.y);const d=Math.abs(u.x-e.x);d>0&&d0&&f{n.x+=i.x,n.y+=i.y})):(ro(e),r=[e.center,...yv(e)]),HNe(s,r,e,!0)}function Wme(s){if(s.type){if(s.type===Kn.Line)return s.calculative.worldAnchors}else{const e=yv(s.calculative.worldRect);return ro(s.calculative.worldRect),[...s.calculative.worldAnchors,...e,s.calculative.worldRect.center]}}function apt(s,e,t,i){const r=yv(e);return HNe(s,r,e)}function HNe(s,e,t,i=!1){let r,n,a=1/0,o=1/0;const l=10,c=dpt(t,l);return s.data.pens.forEach(u=>{const{inView:h,worldRect:d,active:f}=u.calculative;if(h===!1||!i&&f||hpt(c,d)||u.type&&s.active.some(m=>jNe(s,m,u)))return;const p=Wme(u);if(p)for(const m of p)for(const g of e){const _=m.x-g.x,y=m.y-g.y,v=Math.abs(_),x=Math.abs(y);t.center||(t.center={x:t.x+t.width/2,y:t.y+t.height/2}),v{if(e.has(t)&&e.get(t)?s=e.get(t):e.set(t,s=new Map),typeof r!="function")return()=>{console.warn("[rewritePenLifeCycle] warn: not a function ")};let a=new Set,o=new Map;s.has(i)&&s.get(i)?a=s.get(i):(o.set(i,t[i]),s.set(i,a)),n?a.delete(r):a.add(r);let l=o.get(i),c=(...u)=>{l==null||l(...u),a.forEach(h=>{h(...u)})};t[i]=c}}let lpt=opt();function cpt(s){return!s.name&&!s.install?(console.error("installPenPlugin Error: Validation Failed"),!1):!0}function vy(s,e){if(!e)return;if(e.ex==null&&Go(e),!e.rotate||e.rotate%360===0)return s.x>e.x&&s.xe.y&&s.y{Pa(i,e.rotate,e.pivot||e.center)}),upt(s,t)}function TS(s,e,t=0){const{x:i,y:r,ex:n,ey:a}=e;return s.x>=i-t&&s.x<=n+t&&s.y>=r-t&&s.y<=a+t}function ro(s){s.center||(s.center={}),s.center.x=s.x+s.width/2,s.center.y=s.y+s.height/2}function Go(s){s.ex=s.x+s.width,s.ey=s.y+s.height}function eue(s,e){s.pivot||(s.pivot={}),s.pivot.x=s.x+s.width*e.x,s.pivot.y=s.y+s.height*e.y}function upt(s,e){if(e.length<3)return!1;let t=!1,i=e[e.length-1];for(const r of e)i.y>s.y!=r.y>s.y&&r.x+(s.y-r.y)*(i.x-r.x)/(i.y-r.y)>s.x&&(t=!t),i=r;return t}function Um(s){const e=[];s.forEach(i=>{if(i.isRuleLine)return;const r=i.calculative.worldRect;if(r){const n=yv(r);e.push(...n)}});const t=rz(e);return ro(t),t}function yv(s){const e=[{x:s.x,y:s.y},{x:s.ex,y:s.y},{x:s.ex,y:s.ey},{x:s.x,y:s.ey}];return s.rotate&&(s.center||ro(s),e.forEach(t=>{Pa(t,s.rotate,s.pivot||s.center)})),e}function rz(s){let e=1/0,t=1/0,i=-1/0,r=-1/0;return s==null||s.forEach(n=>{!isFinite(n.x)||!isFinite(n.y)||(e=Math.min(e,n.x),t=Math.min(t,n.y),i=Math.max(i,n.x),r=Math.max(r,n.y))}),{x:e,y:t,ex:i,ey:r,width:i-e,height:r-t}}function ov(s,e,t){return s.rotate&&(s=rz(yv(s))),t?s.x>e.x&&s.exe.y&&s.eye.ex||s.exe.ey)}function hpt(s,e){return(e.x>s.ex||e.exs.ey||e.eys.y!=l>s.y&&s.x<(o-n)*(s.y-a)/(l-a)+n&&(t=!t)}return t}const gpt=/^[\t\n\f\r ]*([MLHVZCSQTAmlhvzcsqta])[\t\n\f\r ]*/,cEe=/^[01]/,za=/^[+-]?(([0-9]*\.[0-9]+)|([0-9]+\.)|([0-9]+))([eE][+-]?[0-9]+)?/,_pt=/^(([\t\n\f\r ]+,?[\t\n\f\r ]*)|(,[\t\n\f\r ]*))/,vpt={M:[za,za],L:[za,za],H:[za],V:[za],Z:[],C:[za,za,za,za,za,za],S:[za,za,za,za],Q:[za,za,za,za],T:[za,za],A:[za,za,za,cEe,cEe,za,za]};function ypt(s){let e=0;const t=[];for(;e{n.worldPoints.forEach((a,o)=>{o%2===0?(ai&&(i=a)):(ar&&(r=a))})}),--e,--t,{x:e,y:t,ex:i,ey:r,width:i-e+1,height:r-t+1}}function xpt(s,e,t){t==null&&(t=e),s.commands.forEach((i,r)=>{if(!(i.relative&&r))switch(i.key){case"A":case"a":i.values[5]+=e,i.values[6]+=t;break;case"V":case"v":i.values[0]+=t;break;default:i.values.forEach((n,a)=>{i.values[a]=n+(a%2===0?e:t)});break}})}function Apt(s,e,t){t==null&&(t=e),s.commands.forEach(i=>{switch(i.key){case"A":case"a":const r=i.values[0],n=i.values[1],a=Math.PI*i.values[2]/180,o=Math.cos(a),l=Math.sin(a),c=n*n*t*t*o*o+r*r*t*t*l*l,u=2*e*t*o*l*(n*n-r*r),h=r*r*e*e*o*o+n*n*e*e*l*l,d=-(r*r*n*n*e*e*t*t),f=u*u-4*c*h,p=Math.sqrt((c-h)*(c-h)+u*u);i.values[2]=u!==0?Math.atan((h-c-p)/u)*180/Math.PI:c=0?i.values[4]:1-i.values[4];break;case"V":case"v":i.values[0]*=t;break;default:i.values.forEach((m,g)=>{i.values[g]=m*(g%2===0?e:t)});break}})}function bpt(s){let e="";return s.commands.forEach(t=>{e+=t.key+" ",t.values.forEach(i=>{e+=i+" "})}),e}function Cpt(s,e,t){const i=vpt[s.toUpperCase()],r=[];for(;t<=e.length;){const n={key:s,values:[]};for(const a of i){const o=e.slice(t).match(a);if(o!==null){n.values.push(+o[0]),t+=o[0].length;const l=e.slice(t).match(_pt);l!==null&&(t+=l[0].length)}else{if(n.values.length===0)return{cursor:t,commands:r};throw new Error("malformed path (first error at "+t+")")}}if(n.relative=n.key.toUpperCase()!==n.key,r.push(n),i.length===0)return{cursor:t,commands:r};s==="m"&&(s="l"),s==="M"&&(s="L")}throw new Error("malformed path (first error at "+t+")")}function Spt(s,e){const t=[];let i=s.relative&&e?{x:e.worldPoints[e.worldPoints.length-2],y:e.worldPoints[e.worldPoints.length-1]}:{x:0,y:0};for(let r=0;r{switch(r.key){case"Z":case"z":r.worldPoints=[t,i];break;case"H":r.worldPoints=[r.values[0],e.worldPoints[e.worldPoints.length-1]];break;case"h":r.worldPoints=[r.values[0]+e.worldPoints[e.worldPoints.length-2],e.worldPoints[e.worldPoints.length-1]];break;case"V":r.worldPoints=[e.worldPoints[e.worldPoints.length-2],r.values[0]];break;case"v":r.worldPoints=[e.worldPoints[e.worldPoints.length-2],r.values[0]+e.worldPoints[e.worldPoints.length-1]];break;case"A":r.worldPoints=[e.worldPoints[e.worldPoints.length-2],r.values[0]+e.worldPoints[e.worldPoints.length-1]];break;default:Spt(r,e);break}(r.key==="M"||r.key==="m"||r.key==="Z"||r.key==="z")&&(t=r.worldPoints[r.worldPoints.length-2],i=r.worldPoints[r.worldPoints.length-1]),e=r})}function Tpt(s,e){var l;const i=s.calculative.canvas.store.data.paths[s.pathId];if(!i)return new Path2D;const r=ypt(i);s.calculative.svgRect=uEe(r),ro(s.calculative.svgRect),(s.calculative.svgRect.width!==s.calculative.worldRect.width||s.calculative.svgRect.height!==s.calculative.worldRect.height)&&Apt(r,s.calculative.worldRect.width/s.calculative.svgRect.width,s.calculative.worldRect.height/s.calculative.svgRect.height);const n=uEe(r);ro(n),xpt(r,s.calculative.worldRect.x-n.x,s.calculative.worldRect.y-n.y);const a=bpt(r);if(e){(l=e.svgPath)==null||l.call(e,a);return}return new Path2D(a)}function Mpt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i+n/2,r),t.lineTo(i+n,r+a/2),t.lineTo(i+n/2,r+a),t.lineTo(i,r+a/2),t.lineTo(i+n/2,r),t.closePath(),t instanceof Path2D)return t}function Rpt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i+n/2,r),t.lineTo(i+n,r+a),t.lineTo(i,r+a),t.lineTo(i+n/2,r),t.closePath(),t instanceof Path2D)return t}function Ipt(s){const e=[{x:.5,y:0},{x:.75,y:.5},{x:.5,y:1},{x:.25,y:.5}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function Ppt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i+n/2,r),t.lineTo(i+n,r+a*2/5),t.lineTo(i+n*4/5,r+a),t.lineTo(i+n/5,r+a),t.lineTo(i,r+a*2/5),t.closePath(),t instanceof Path2D)return t}function wpt(s){const e=[{x:.5,y:0},{x:1,y:.4},{x:.8,y:1},{x:.2,y:1},{x:0,y:.4}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function Dpt(s,e){s.onResize||(s.onResize=Lpt);const t=e||new Path2D,{width:i,height:r,center:n}=s.calculative.worldRect,a=i>r?r:i,o=n.x,l=n.y,c=l-a/2,u=l-a/4,h=-(u-l)*Math.sin(Math.PI/180*324)+o,d=(u-l)*Math.cos(Math.PI/180*324)+l;t.moveTo(h,d);for(let f=0;f<5;++f)t.lineTo(-(c-l)*Math.sin(Math.PI/180*72*f)+o,(c-l)*Math.cos(Math.PI/180*72*f)+l),t.lineTo((h-o)*Math.cos(Math.PI/180*72*(f+1))-(d-l)*Math.sin(Math.PI/180*72*(f+1))+o,(h-o)*Math.sin(Math.PI/180*72*(f+1))+(d-l)*Math.cos(Math.PI/180*72*(f+1))+l);if(t.closePath(),t instanceof Path2D)return t}function XNe(s){const{width:e,height:t}=s,i=e>t?t:e,r=[];for(let n=0;n<5;++n)r.push({flag:1,id:String(n),penId:s.id,x:.5+i/2*Math.sin(Math.PI/180*72*n)/e,y:-i/2*Math.cos(Math.PI/180*72*n)/t+.5});s.anchors=r}function Lpt(s){const e=s.anchors.filter(t=>t.flag!==1);XNe(s),s.anchors=s.anchors.concat(...e)}function Opt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i+n/4,r),t.lineTo(i+n*3/4,r),t.lineTo(i+n,r+a/2),t.lineTo(i+n*3/4,r+a),t.lineTo(i+n*1/4,r+a),t.lineTo(i,r+a/2),t.lineTo(i+n/4,r),t.closePath(),t instanceof Path2D)return t}function Npt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i,r+a/2),t.lineTo(i+a/2,r),t.lineTo(i+a/2,r+a/3),t.lineTo(i+n,r+a/3),t.lineTo(i+n,r+a*2/3),t.lineTo(i+a/2,r+a*2/3),t.lineTo(i+a/2,r+a*2/3),t.lineTo(i+a/2,r+a),t.closePath(),t instanceof Path2D)return t}function Fpt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i,r+a/3),t.lineTo(i+(n-a/2),r+a/3),t.lineTo(i+(n-a/2),r),t.lineTo(i+n,r+a/2),t.lineTo(i+(n-a/2),r+a),t.lineTo(i+(n-a/2),r+a*2/3),t.lineTo(i,r+a*2/3),t.closePath(),t instanceof Path2D)return t}function Bpt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i,r+a/2),t.lineTo(i+a/2,r),t.lineTo(i+a/2,r+a/3),t.lineTo(i+(n-a/2),r+a/3),t.lineTo(i+(n-a/2),r),t.lineTo(i+n,r+a/2),t.lineTo(i+(n-a/2),r+a),t.lineTo(i+(n-a/2),r+a*2/3),t.lineTo(i+a/2,r+a*2/3),t.lineTo(i+a/2,r+a),t.closePath(),t instanceof Path2D)return t}function kpt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a,ey:o}=s.calculative.worldRect;if(t.moveTo(i,r),t.lineTo(i+n,r),t.lineTo(i+n,r+a*3/4),t.lineTo(i+n*8/16,r+a*3/4),t.lineTo(i+n/4,o),t.lineTo(i+n*5/16,r+a*3/4),t.lineTo(i,r+a*3/4),t.closePath(),t instanceof Path2D)return t}function Upt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.moveTo(i+n/5,r+a*13/16),t.bezierCurveTo(i-n/15,r+a*13/16,i-n/15,r+a*7/16,i+n/5,r+a*7/16),t.bezierCurveTo(i+n/5,r,i+n*4/5,r,i+n*4/5,r+a*7/16),t.bezierCurveTo(i+n*16/15,r+a*7/16,i+n*16/15,r+a*13/16,i+n*4/5,r+a*13/16),t.closePath(),t instanceof Path2D)return t}function zpt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,ex:a,ey:o}=s.calculative.worldRect,l=n/6;if(t.moveTo(i,r),t.lineTo(a-l,r),t.lineTo(a,r+l),t.lineTo(a,o),t.lineTo(i,o),t.closePath(),t.moveTo(a-l,r),t.lineTo(a-l,r+l),t.lineTo(a,r+l),t.closePath(),t instanceof Path2D)return t}function Vpt(s,e){const{x:t,y:i,width:r,ex:n,ey:a}=e.calculative.worldRect;let o=r*.25;const l=e.z;l>1?o=l:l>0&&(o=r*l);const c={x:t,y:i+o},u={x:n-o,y:i+o},h={x:n-o,y:a};Nse(s,[c,u,h,{x:t,y:a}],e.backgroundFront||e.background,e.color),Nse(s,[c,{x:t+o,y:i},{x:n,y:i},u],e.backgroundUp||e.background,e.color),Nse(s,[u,{x:n,y:i},{x:n,y:a-o},h],e.backgroundRight||e.background,e.color)}function Nse(s,e,t="",i=""){s.save(),t&&(s.fillStyle=t),i&&(s.strokeStyle=i),s.beginPath();for(let r=0;ri.x?o=Ts.Right:o=Ts.Left),i.next={id:fs(),penId:e.id,x:i.x,y:i.y,prevNextType:2},r.prev={id:fs(),penId:e.id,x:r.x,y:r.y,prevNextType:2},o){case Ts.Up:i.next.y-=n,r.prev.y=i.y;break;case Ts.Bottom:i.next.y+=n,r.prev.y=i.y;break;case Ts.Left:i.next.x-=n,r.prev.x=i.x;break;default:i.next.x+=n,r.prev.x=i.x;break}}function jpt(s,e){const t=e||new Path2D;if((s.lineName==="line"||s.lineName==="polyline")&&s.calculative.lineSmooth){let r=Ume(s);if(t instanceof Path2D&&t.addPath(r),t instanceof Path2D)return t}const i=s.calculative.worldAnchors;if(i.length>1){let r;i.forEach(n=>{r?dEe(t,r,n):n.start=!0,r=n}),s.close&&(s.lineName==="curve"?dEe(t,r,i[0]):t.closePath())}if(t instanceof Path2D)return t}function Xpt(s,e,t){var n;if(e.calculative.worldAnchors||(e.calculative.worldAnchors=[]),e.calculative.worldAnchors.length<2||((n=e.anchors)==null?void 0:n.length)>1)return;const i=rl(e),r=Dn(e);!i||!r||!r.id||i===r||(i.next=void 0,Vme(e),r.prev=void 0,e.calculative.worldAnchors.push(r))}function dEe(s,e,t){!t||t.isTemp||(e.start&&s.moveTo(e.x,e.y),e.next?t.prev?s.bezierCurveTo(e.next.x,e.next.y,t.prev.x,t.prev.y,t.x,t.y):s.quadraticCurveTo(e.next.x,e.next.y,t.x,t.y):t.prev?s.quadraticCurveTo(t.prev.x,t.prev.y,t.x,t.y):s.lineTo(t.x,t.y))}function rue(s){return sue(s),rz(QNe(s))}function QNe(s){const e=[];let t;return s.calculative.worldAnchors.forEach(i=>{e.push(i),t&&e.push(...fEe(t,i,s)),t=i}),s.close&&s.calculative.worldAnchors.length>1&&e.push(...fEe(t,s.calculative.worldAnchors[0],s)),e}function q$(s){return s!=null&&s.lineWidth?s.lineWidth/2+4:4}function fEe(s,e,t){const i=[];if(!e)return i;let r=.02;if(s.lineLength&&(r=q$(t)/s.lineLength),s.next)if(e.prev)for(let n=r;n<1;n+=r)i.push(YNe(n,s,s.next,e.prev,e));else for(let n=r;n<1;n+=r)i.push(iue(n,s,s.next,e));else if(e.prev)for(let n=r;n<1;n+=r)i.push(iue(n,s,e.prev,e));else i.push({x:e.x,y:e.y});return i.length>1&&(s.curvePoints=i),i}function Ypt(s,e){const t=q$(e);let i=0,r,n;for(const a of e.calculative.worldAnchors){if(r){if(n=pEe(s,r,a,t),n)return{i,point:n};++i}r=a}if(e.close&&e.calculative.worldAnchors.length>1&&(n=pEe(s,r,e.calculative.worldAnchors[0],t)))return{i,point:n}}function pEe(s,e,t,i=4){if(!e.next&&!t.prev){const{x:r,y:n}=e,{x:a,y:o}=t,l=Math.min(r,a),c=Math.max(r,a),u=Math.min(n,o),h=Math.max(n,o);return s.x>=l-i&&s.x<=c+i&&s.y>=u-i&&s.y<=h+i?Qpt(s,e,t,i):void 0}else if(e.curvePoints){for(const r of e.curvePoints)if(g5(s,r,i))return r}}function Qpt(s,e,t,i=4){if(e.x===t.x){if(Math.abs(s.x-e.x)<=i)return{x:e.x,y:s.y}}else{const r=(e.y-t.y)/(e.x-t.x),n=e.y-r*e.x;if(Math.abs((r*s.x+n-s.y)/Math.sqrt(r*r+1))<=i){const l=(s.x+r*s.y-r*n)/(r*r+1);return{x:l,y:r*l+n}}}}function mEe(s,e,t,i){if(!e&&!t)return Math.sqrt(Math.pow(Math.abs(s.x-i.x),2)+Math.pow(Math.abs(s.y-i.y),2))||0;const r=document.createElementNS("http://www.w3.org/2000/svg","path");return e&&t?r.setAttribute("d",`M${s.x} ${s.y} C${e.x} ${e.y} ${t.x} ${t.y} ${i.x} ${i.y}`):e?r.setAttribute("d",`M${s.x} ${s.y} Q${e.x} ${e.y} ${i.x} ${i.y}`):r.setAttribute("d",`M${s.x} ${s.y} Q${t.x} ${t.y} ${i.x} ${i.y}`),r.getTotalLength()||0}function sue(s){if(s.calculative.worldAnchors.length<2)return 0;let e=0,t;if(s.calculative.worldAnchors.forEach(i=>{t&&(t.lineLength=mEe(t,t.next,i.prev,i),e+=t.lineLength),t=i}),s.close){const i=rl(s);t.lineLength=mEe(t,t.next,i.prev,i),e+=t.lineLength}return s.calculative.animatePos&&(s.calculative.animatePos=e/s.length*s.calculative.animatePos),s.length=e,e}function Fse(s,e){const t=s.calculative.worldAnchors;for(let i=0;i=0&&h*c+d*u+f<=0||h*o+d*l+f<=0&&h*c+d*u+f>=0||h*o+d*u+f>=0&&h*c+d*l+f<=0||h*o+d*u+f<=0&&h*c+d*l+f>=0){if(o>c){const p=o;o=c,c=p}if(lc&&n>c||r>l&&a>l||rf.y&&i.yf.y))){p=d;let g=Vd;i.x{g.id=fs(),g.penId=e.id,e.calculative.worldAnchors.push(g)}),e.calculative.worldAnchors.push(r),p&&e.calculative.worldAnchors.push(p),d&&e.calculative.worldAnchors.push(f),n&&e.calculative.worldAnchors.reverse(),a){const g=e.calculative.worldAnchors.length-2;e.calculative.worldAnchors[g].isTemp=!1,e.calculative.worldAnchors[1].isTemp=!1}}function gEe(s,e,t){const i={x:s.x,y:s.y,id:fs()};switch(e){case Ts.Up:i.y-=t;break;case Ts.Right:i.x+=t;break;case Ts.Bottom:i.y+=t;break;case Ts.Left:i.x-=t;break;default:return}return i}function qpt(s,e,t){if(s.x===e.x||s.y===e.y)return[];const i=[];let r,n;switch(t){case Ts.Up:s.ys.y)r=s.x+(e.x-s.x)/2,i.push({x:r,y:s.y},{x:r,y:e.y});else{const a=(s.y+e.y)/2;i.push({x:s.x,y:a},{x:e.x,y:a})}break;case Ts.Right:r=e.x,n=s.y,e.xs.x&&e.ys.y-Vd)r=s.x+(e.x-s.x)/2,i.push({x:r,y:s.y},{x:r,y:e.y});else{const a=(s.y+e.y+Vd)/2;i.push({x:s.x,y:a},{x:e.x,y:a})}break}return i}function Jpt(s,e,t){if(s.x===e.x||s.y===e.y)return[];const i=[];let r,n;switch(t){case Ts.Up:r=s.x,n=e.y,e.x>s.x&&e.y>s.y&&(r=e.x,n=s.y),i.push({x:r,y:n});break;case Ts.Bottom:r=s.x,n=e.y,e.x>s.x&&e.ys.y&&(r=s.x,n=e.y),i.push({x:r,y:n});break;case Ts.Bottom:s.y>e.y?(r=e.x,n=s.y):(r=s.x,n=e.y),i.push({x:r,y:n});break;case Ts.Left:r=e.x,n=s.y,e.x>s.x&&e.y>s.y&&(r=s.x,n=e.y),i.push({x:r,y:n});break;default:if(r=s.x,e.ys.y&&(r=e.x,n=s.y),i.push({x:r,y:n});break;case Ts.Bottom:r=s.x,n=e.y,e.xs.x)r=e.x,n=s.y+(e.y-s.y)/2,i.push({x:s.x,y:n},{x:e.x,y:n});else{const a=(s.x+e.x)/2;i.push({x:a,y:s.y},{x:a,y:e.y})}break;case Ts.Left:e.x>s.x?i.push({x:s.x,y:e.y}):i.push({x:e.x,y:s.y});break;default:if(r=s.x,n=e.y,e.xMath.abs(t.y-e.y));let r=s.calculative.worldAnchors.findIndex(n=>n.id==e.id);if(r>1){let n=s.calculative.worldAnchors[r-1];if(n.x===e.x&&n.y!==e.y)return i.push({x:t.x,y:e.y}),i;if(n.y===e.y&&n.x!==e.x)return i.push({x:e.x,y:t.y}),i}return s.calculative.worldAnchors.length&&(t.isTemp=void 0,s.calculative.drawlineH?(i.push({x:t.x,y:e.y}),Math.abs(t.y-e.y){i.unshift(a)}));for(let a=0;a{i.unshift(a)}));for(let a=0;al.id===e.id),r=rl(s),n=Dn(s);let a=s.calculative.worldAnchors[i-1],o=s.calculative.worldAnchors[i+1];if(s.calculative.h==null&&(r.connectTo&&(JX(s,e,!0)?s.calculative.h=!0:eY(s,e,!0)&&(s.calculative.h=!1)),s.calculative.h==null&&n.connectTo&&(JX(s,e,!1)?s.calculative.h=!0:eY(s,e,!1)&&(s.calculative.h=!1)),s.calculative.h==null&&(a?s.calculative.h=a.y===e.y:o&&(s.calculative.h=o.y===e.y))),s.calculative.h){if(e.x=t.x,r.connectTo&&JX(s,e,!0)){o&&o.y!==e.y&&(o.x=e.x);return}if(n.connectTo&&JX(s,e,!1)){a&&a.y!==e.y&&(a.x=e.x);return}const l=s.anchors[i];let c;for(let u=i-1;u>-1;u--)if(a=s.anchors[u],c==null&&(c=a.y===l.y),c===!0)if(a.y===l.y)s.calculative.worldAnchors[u].y=t.y;else break;else if(a.x===l.x)s.calculative.worldAnchors[u].x=t.x;else break;c=void 0;for(let u=i+1;u-1;u--)if(a=s.anchors[u],c==null&&(c=a.x===l.x),c===!0)if(a.x===l.x)s.calculative.worldAnchors[u].x=t.x;else break;else if(a.y===l.y)s.calculative.worldAnchors[u].y=t.y;else break;c=void 0;for(let u=i+1;u1?(c=m.x-p.x,u=m.y-p.y):g>0?(c=m.x-(o+h*g),u=m.y-(l+d*g)):(c=m.x-o,u=m.y-l)):(c=m.x-o,u=m.y-l),_=c*c+u*u,_>n&&(a=v,n=_);return n>e&&(a-t>1&&r.push(...nue(s,e,t,a)),r.push({id:s[a].id,penId:s[a].penId,x:s[a].x,y:s[a].y}),i-a>1&&r.push(...nue(s,e,a,i))),r}function s0t(s,e=.8,t=!1){if(s.length<3)return s;let i,r,n,a,o,l,c,u,h,d,f,p,m,g,_;const y=(v,x,A,b)=>(a=Math.sqrt(v*v+x*x),a>0?(p=v/a,g=x/a):(p=1,g=0),o=Math.sqrt(A*A+b*b),o>0?(m=A/o,_=b/o):(m=1,_=0),Math.acos(p*m+g*_));d=[],f=s.length,i=s[0],s[f-1],d.push({...s[0]});for(let v=0;v1){let u,h=0;for(let d=0;da)&&g>l+a&&_-g>l&&(s.lineAnimateType===u0.Arrow?a0t(t,m,n,p,c,a):s.lineAnimateType===u0.WaterDrop&&o0t(t,m,s.animateReverse,p,c,a)),m.x+=o*Math.cos(p*Math.PI/180),m.y-=o*Math.sin(p*Math.PI/180),g=Math.sqrt((m.x-u.x)**2+(m.y-u.y)**2)}u=f}}if(t instanceof Path2D)return t}function n0t(s,e){let t=e.x-s.x,i=e.y-s.y,r=Math.atan(i/t)*180/Math.PI;return e.x>=s.x?r=-r:r=180-r,r}function Cy(s,e,t){let i=(180-t)*Math.PI/180;return{x:(s.x-e.x)*Math.cos(i)-(s.y-e.y)*Math.sin(i)+e.x,y:(s.x-e.x)*Math.sin(i)+(s.y-e.y)*Math.cos(i)+e.y}}function a0t(s,e,t,i,r,n){let a=Cy({x:e.x+t,y:e.y+.57*t},{x:e.x,y:e.y},i),o=Cy({x:e.x+t,y:e.y-.57*t},{x:e.x,y:e.y},i),l=Cy({x:e.x+t,y:e.y+r/2},{x:e.x,y:e.y},i),c=Cy({x:e.x+n,y:e.y+r/2},{x:e.x,y:e.y},i),u=Cy({x:e.x+t,y:e.y-r/2},{x:e.x,y:e.y},i),h=Cy({x:e.x+n,y:e.y-r/2},{x:e.x,y:e.y},i);s.moveTo(a.x,a.y),s.lineTo(e.x,e.y),s.lineTo(o.x,o.y),s.lineTo(u.x,u.y),s.lineTo(h.x,h.y),s.lineTo(c.x,c.y),s.lineTo(l.x,l.y),s.lineTo(a.x,a.y)}function o0t(s,e,t,i,r,n){let a=r/2;t&&(a=-r/2);let o=Cy({x:e.x,y:e.y+a},{x:e.x,y:e.y},i),l=Cy({x:e.x+n,y:e.y},{x:e.x,y:e.y},i),c=Math.PI/2;t&&(c=-Math.PI/2),s.moveTo(e.x,e.y),s.arc(e.x,e.y,r/2,-c-i/180*Math.PI,c-i/180*Math.PI,!1),s.lineTo(l.x,l.y),s.lineTo(o.x,o.y)}function l0t(s){var t;s.onDestroy||(s.onDestroy=c0t,s.onMove=tY,s.onResize=tY,s.onRotate=tY,s.onValue=tY,s.onMouseMove=h0t,s.onBeforeValue=u0t,s.onRenderPenRaw=d0t),s.calculative.singleton||(s.calculative.singleton={});const e=s.calculative.worldRect;if(!s.calculative.singleton.div){const i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="-9999px",i.style.top="-9999px",i.style.width=e.width+"px",i.style.height=e.height+"px",document.body.appendChild(i),(t=s.calculative.canvas.externalElements)==null||t.parentElement.appendChild(i),Ha(s,i),s.calculative.singleton.div=i;const r=document.createElement("iframe");r.style.width="100%",r.style.height="100%",r.scrolling=s.scrolling||"no",r.frameBorder="0",r.style.border="none",r.src=s.iframe,s.calculative.iframe=s.iframe,i.appendChild(r),JNe(s),r.onload=()=>{r.setAttribute("document.domain","")}}return s.calculative.patchFlags&&Ha(s,s.calculative.singleton.div),s.onRenderPenRaw(s),new Path2D}function c0t(s){eFe(s),s.calculative.singleton&&s.calculative.singleton.div&&(s.calculative.singleton.div.remove(),delete s.calculative.singleton.div)}function tY(s){s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div)}function u0t(s,e){if(e.iframe&&s.calculative.singleton.div&&(s.calculative.singleton.div.children[0].src=e.iframe,s.calculative.iframe=e.iframe),e.operationalRect||e["operationalRect.x"]!==void 0||e["operationalRect.y"]!==void 0||e["operationalRect.width"]!==void 0||e["operationalRect.height"]!==void 0){s.operationalRect||(s.operationalRect={});let t=bt(e);t.operationalRect||(t.operationalRect={}),t["operationalRect.x"]!==void 0&&(t.operationalRect.x=t["operationalRect.x"]),t["operationalRect.y"]!==void 0&&(t.operationalRect.y=t["operationalRect.y"]),t["operationalRect.width"]!==void 0&&(t.operationalRect.width=t["operationalRect.width"]),t["operationalRect.height"]!==void 0&&(t.operationalRect.height=t["operationalRect.height"]),Object.assign(s.operationalRect,t.operationalRect),s.calculative.singleton.div&&(s.calculative.singleton.div.children.length===1?JNe(s):(s.calculative.singleton.div.children[1].style.height=s.operationalRect.y*100+"%",s.calculative.singleton.div.children[1].style.left=s.operationalRect.x*100+"%",s.calculative.singleton.div.children[1].style.width=s.operationalRect.width*100+"%",s.calculative.singleton.div.children[2].style.width=(1-s.operationalRect.x-s.operationalRect.width)*100+"%",s.calculative.singleton.div.children[3].style.height=(1-s.operationalRect.y-s.operationalRect.height)*100+"%",s.calculative.singleton.div.children[3].style.left=s.operationalRect.x*100+"%",s.calculative.singleton.div.children[3].style.width=s.operationalRect.width*100+"%",s.calculative.singleton.div.children[4].style.width=s.operationalRect.x*100+"%"))}if(e.blur!==void 0)for(let t=1;t<5;t++)s.calculative.singleton.div.children[t].style["backdrop-filter"]=`blur(${e.blur||2}px)`;if(e.blurBackground!==void 0)for(let t=1;t<5;t++)s.calculative.singleton.div.children[t].style.backgroundColor=e.blurBackground;return e}function h0t(s,e){if(!(!s.calculative.canvas.store.data.locked&&!s.locked)&&qNe(s.operationalRect)&&s.calculative.zIndex<5&&e.x>s.x+s.width*s.operationalRect.x&&e.xs.y+s.height*s.operationalRect.y&&e.y{eFe(s)};t.onmouseenter=a,r.onmouseenter=a,i.onmouseenter=a,n.onmouseenter=a,e.onmouseleave=a}function eFe(s){if(!(!s.calculative.canvas.store.data.locked&&!s.locked)&&s.calculative.zIndex<5){let e=s.calculative.singleton.div.parentNode.children;for(let t=1;t<6;t++)e[t].style.pointerEvents="initial"}}function d0t(s){if(s.thumbImg&&!s.calculative.img){const e=new Image;e.crossOrigin=s.crossOrigin==="undefined"?void 0:s.crossOrigin||"anonymous",s.calculative.canvas.store.options.cdn&&!(s.thumbImg.startsWith("http")||s.thumbImg.startsWith("//")||s.thumbImg.startsWith("data:image"))?e.src=s.calculative.canvas.store.options.cdn+s.thumbImg:e.src=s.thumbImg,e.onerror=t=>{e.remove(),s.calculative.img=void 0},s.calculative.img=e}}const Gd={},WQ=['',''];function f0t(s){var e;if(s.onDestroy||(s.onDestroy=p0t,s.onMove=Bse,s.onResize=Bse,s.onRotate=Bse,s.onClick=_Ee,s.onValue=g0t,s.onChangeId=m0t),Gd[s.id])s.video&&s.calculative.media&&s.video!==s.calculative.video?(console.warn("video 更改, 此处是否执行?"),s.calculative.media.src=s.video,s.autoPlay&&(s.calculative.media.muted=!0,s.calculative.media.autoplay=!0),s.calculative.media.loop=s.playLoop,s.calculative.video=s.video):s.audio&&s.calculative.media&&s.audio!==s.calculative.audio&&(s.calculative.media.src=s.audio,s.autoPlay&&(s.calculative.media.muted=!0,s.calculative.media.autoplay=!0),s.calculative.media.loop=s.playLoop,s.calculative.audio=s.audio);else{const t=document.createElement("div"),i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="0",i.style.bottom="0",i.style.width="0",i.style.height="2px",i.style.background="#52c41a",i.style.zIndex="1",s.hideProgress&&(i.style.display="none");const r=document.createElement("div");r.innerHTML=WQ[1],r.style.position="absolute",r.style.right="0",r.style.bottom="0",r.style.width="20px",r.style.height="20px",r.style.fill="hsla(0, 0%, 100%, .8)",r.style.zIndex="1",r.style.display="none",t.appendChild(i),t.appendChild(r),r.onclick=a=>{a.stopPropagation(),s.calculative.media.muted?(r.innerHTML=WQ[0],s.calculative.media.muted=!1):(r.innerHTML=WQ[1],s.calculative.media.muted=!0)},s.calculative.singleton||(s.calculative.singleton={}),s.calculative.singleton.muted=r,t.onmouseenter=a=>{r.style.display="block"},t.onmouseleave=a=>{r.style.display="none"},t.onclick=a=>{a.stopPropagation(),_Ee(s)};let n;s.video?(n=document.createElement("video"),n.src=s.video):s.audio&&(n=document.createElement("audio"),n.controls=s.controls,n.src=s.audio),n.loop=s.playLoop,n.ontimeupdate=()=>{tFe(i,n,s.calculative.worldRect.width)},n.onended=()=>{s.calculative.onended&&s.calculative.onended(s)},s.calculative.media=n,n.style.position="absolute",n.style.outline="none",n.style.left="0",n.style.top="0",n.style.width="100%",n.style.height="100%",t.appendChild(n),Gd[s.id]=t,(e=s.calculative.canvas.externalElements)==null||e.parentElement.appendChild(t),Ha(s,t),s.autoPlay&&(n.autoplay=!0,n.muted=!0)}return s.calculative.patchFlags&&Ha(s,Gd[s.id]),new Path2D}function p0t(s){Gd[s.id].onclick=null,Gd[s.id].remove(),Gd[s.id]=void 0}function Bse(s){Ha(s,Gd[s.id]);const e=Gd[s.id].children[0],t=Gd[s.id].children[1];tFe(e,t,s.calculative.worldRect.width)}function _Ee(s){s.calculative.media&&(s.calculative.media.muted=!1,s.calculative.singleton.muted.innerHTML=WQ[0],s.calculative.media.paused?s.calculative.media.play():s.calculative.media.pause())}function tFe(s,e,t){s.style.width=e.currentTime/e.duration*t+"px"}function m0t(s,e,t){Gd[e]&&(Gd[t]=Gd[e],delete Gd[e])}function g0t(s){const e=Gd[s.id];if(!e)return;Ha(s,e);const t=s.calculative.media.getAttribute("src");s.video?t!==s.video&&(s.calculative.media.src=s.video):s.audio&&t!==s.audio&&(s.calculative.media.src=s.audio),s.autoPlay&&(s.calculative.media.muted=!0,s.calculative.media.autoplay=!0),s.calculative.media.loop=s.playLoop}function G1(){try{const s=new OffscreenCanvas(0,0),e=s.getContext("2d");return e&&e.arc?s:document.createElement("canvas")}catch{return document.createElement("canvas")}}class UB{constructor(e,t){ke(this,"box");ke(this,"text");ke(this,"arrowUp");ke(this,"arrowDown");ke(this,"x");ke(this,"y");ke(this,"currentPen");this.parentElement=e,this.store=t,this.box=document.createElement("div"),this.text=document.createElement("div"),this.arrowUp=document.createElement("div"),this.arrowDown=document.createElement("div"),this.box.className="meta2d-tooltip",this.text.className="text",this.arrowUp.className="arrow",this.arrowDown.className="arrow down",this.box.appendChild(this.text),this.box.appendChild(this.arrowUp),this.box.appendChild(this.arrowDown),e.appendChild(this.box),this.box.onmouseleave=()=>{this.hide(),this.store.lastHover=void 0};let i;for(let r=0;r0?(this.arrowUp.style.borderBottomColor="transparent",this.arrowDown.style.borderTopColor="#777777"):(a+=i.height+r.height+5,this.arrowUp.style.borderBottomColor="#777777",this.arrowDown.style.borderTopColor="transparent"),this.x=n,this.y=a,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px"}hide(){this.currentPen=null,this.x=-9999,this.box.style.left="-9999px"}translate(e,t){this.x<-1e3||(this.x+=e,this.y+=t,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px")}destroy(){this.box.onmouseleave=null}}class iFe{constructor(e){ke(this,"h");ke(this,"v");ke(this,"isDownH");ke(this,"isDownV");ke(this,"x");ke(this,"y");ke(this,"hSize");ke(this,"vSize");ke(this,"scrollX");ke(this,"scrollY");ke(this,"lastScrollX");ke(this,"lastScrollY");ke(this,"rect");ke(this,"isShow");ke(this,"pageMode");ke(this,"onMouseDownH",e=>{e.preventDefault(),e.stopPropagation(),this.isDownH=e.x,this.x=this.parent.store.data.x||0,this.lastScrollX=this.scrollX});ke(this,"onMouseDownV",e=>{e.preventDefault(),e.stopPropagation(),this.isDownV=e.y,this.y=this.parent.store.data.y||0,this.lastScrollY=this.scrollY});ke(this,"onMouseMove",e=>{if(this.isDownH){const t=e.x-this.isDownH;this.scrollX=this.lastScrollX+t,this.h.style.left=`${this.scrollX}px`,this.parent.store.data.x=this.x-t*this.rect.width/this.parent.parentElement.clientWidth}if(this.isDownV){const t=e.y-this.isDownV;if(this.pageMode&&this.canMouseMove(t))return;this.scrollY=this.lastScrollY+t,this.v.style.top=`${this.scrollY}px`,this.parent.store.data.y=this.y-t*this.rect.height/this.parent.parentElement.clientHeight}(this.isDownH||this.isDownV)&&(this.parent.onMovePens(),this.parent.canvasTemplate.init(),this.parent.canvasImage.init(),this.parent.canvasImageBottom.init(),this.parent.render())});ke(this,"onMouseUp",e=>{!this.isDownH&&!this.isDownV||(this.isDownH=void 0,this.isDownV=void 0,this.scrollX<20?(this.scrollX=20,this.h.style.left=`${this.scrollX}px`):this.scrollX>this.parent.parentElement.clientWidth-this.hSize-20&&(this.scrollX=this.parent.parentElement.clientWidth-this.hSize-20,this.h.style.left=`${this.scrollX}px`),this.scrollY<20?(this.scrollY=20,this.v.style.top=`${this.scrollY}px`):this.scrollY>this.parent.parentElement.clientHeight-this.vSize-20&&(this.scrollY=this.parent.parentElement.clientHeight-this.vSize-20,this.v.style.top=`${this.scrollY}px`),this.resize())});this.parent=e,this.h=document.createElement("div"),this.v=document.createElement("div"),this.parent.externalElements.appendChild(this.h),this.parent.externalElements.appendChild(this.v),this.h.className="meta2d-scroll h",this.h.onmousedown=this.onMouseDownH,this.v.className="meta2d-scroll v",this.v.onmousedown=this.onMouseDownV,document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp);let t;for(let i=0;i=0||e>0&&t.ey-this.parent.height+this.parent.store.data.y<=0}changeMode(){this.pageMode=!0,this.h.style.display="none",this.parent.parent.getRect().height0?this.rect.width+=this.parent.store.data.x+(this.rect.x>0?0:this.rect.x):this.rect.width-=this.parent.store.data.x+(this.rect.x>0?0:this.rect.x),this.parent.store.data.y>0?this.rect.height+=this.parent.store.data.y+(this.rect.y>0?0:this.rect.y):this.rect.height-=this.parent.store.data.y+(this.rect.y>0?0:this.rect.y),this.rect.width<1400&&(this.rect.width=1400),this.rect.height<900&&(this.rect.height=900),this.hSize=1e3*this.parent.parentElement.clientWidth/this.rect.width/3,this.vSize=1e3*this.parent.parentElement.clientHeight/this.rect.height/3,this.h.style.width=this.hSize+"px",this.v.style.height=this.vSize+"px"}show(){this.isShow=!0,this.h.style.display="block",this.v.style.display="block",document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}hide(){this.isShow=!1,this.h.style.display="none",this.v.style.display="none",this.destroy()}translate(e,t){e&&(this.scrollX-=e*this.parent.parentElement.clientWidth/this.rect.width,this.h.style.left=`${this.scrollX}px`),t&&(this.scrollY-=t*this.parent.parentElement.clientHeight/this.rect.height,this.v.style.top=`${this.scrollY}px`)}wheel(e){let t=10;e&&(t=-10),!(this.pageMode&&this.canMouseMove(t))&&(this.scrollY+=t,this.v.style.top=`${this.scrollY}px`,this.parent.store.data.y-=t*this.rect.height/this.parent.parentElement.clientHeight,this.parent.onMovePens(),this.parent.canvasTemplate.init(),this.parent.canvasImage.init(),this.parent.canvasImageBottom.init(),this.parent.render())}destroy(){document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}}class vEe{constructor(e,t,i){ke(this,"canvas",document.createElement("canvas"));ke(this,"otherOffsreen",G1());ke(this,"offscreen",G1());ke(this,"animateOffsScreen",G1());ke(this,"fitOffscreen",G1());ke(this,"fitFlag",!1);ke(this,"currentFit");ke(this,"activeFit");this.parentElement=e,this.store=t,this.isBottom=i,e.appendChild(this.canvas),this.canvas.style.backgroundRepeat="no-repeat",this.canvas.style.backgroundSize="100% 100%",this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0"}resize(e,t){this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",e=e*this.store.dpiRatio|0,t=t*this.store.dpiRatio|0,this.canvas.width=e,this.canvas.height=t,this.otherOffsreen.width=e,this.otherOffsreen.height=t,this.offscreen.width=e,this.offscreen.height=t,this.animateOffsScreen.width=e,this.animateOffsScreen.height=t,this.fitOffscreen.width=e,this.fitOffscreen.height=t,this.otherOffsreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.otherOffsreen.getContext("2d").textBaseline="middle",this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle",this.animateOffsScreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.animateOffsScreen.getContext("2d").textBaseline="middle",this.fitOffscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.fitOffscreen.getContext("2d").textBaseline="middle",this.init()}init(){this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.animateOffsScreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.fitOffscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height);for(const e of this.store.data.pens)this.hasImage(e)&&(e.calculative.imageDrawed=!1);this.isBottom?this.store.patchFlagsBackground=!0:this.store.patchFlagsTop=!0}clear(){this.otherOffsreen.getContext("2d").clearRect(0,0,this.otherOffsreen.width,this.otherOffsreen.height),this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.animateOffsScreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.fitOffscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}hasImage(e){return e.calculative.hasImage=e.calculative&&e.calculative.inView&&(this.isBottom&&e.canvasLayer===hn.CanvasImageBottom||!this.isBottom&&e.canvasLayer===hn.CanvasImage)&&e.image&&e.calculative.img&&e.name!=="gif",e.calculative.hasImage}render(){var a;let e=!1,t=!1;for(const o of this.store.data.pens)this.hasImage(o)&&(this.store.animates.has(o)?t=!0:o.calculative.imageDrawed||(e=!0),o.parentId&&this.store.animates.has(Uf(o,!0))&&(t=!0));const i=this.store.patchFlagsBackground,r=this.store.patchFlagsTop;if(r&&!this.isBottom){const o=this.otherOffsreen.getContext("2d");o.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderRule(o)}if(this.store.patchFlagsLast&&this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),e){const o=this.offscreen.getContext("2d");o.save(),o.clearRect(0,0,this.canvas.width,this.canvas.height),o.translate(this.store.data.x,this.store.data.y);for(const l of this.store.data.pens)!l.calculative.hasImage||this.store.animates.has(l)||this.store.animates.has(Uf(l,!0))||l.canvasLayer!==hn.CanvasTemplate&&(l.name==="combine"&&!l.draw||(l.calculative.imageDrawed=!0,o.save(),SS(o,l),l.calculative.rotate&&vv(o,l),ES(o,l),J5(o,l),o.restore()));o.restore()}if(t){const o=this.animateOffsScreen.getContext("2d");o.save(),o.clearRect(0,0,this.canvas.width,this.canvas.height),o.translate(this.store.data.x,this.store.data.y);for(const l of this.store.animates)l.calculative.hasImage&&l.canvasLayer!==hn.CanvasTemplate&&(l.visible===!1||l.calculative.visible===!1||(l.calculative.imageDrawed=!0,o.save(),SS(o,l),l.calculative.rotate&&vv(o,l),ES(o,l),J5(o,l),o.restore()));for(const l of this.store.data.pens)!l.calculative.hasImage||!l.parentId||l.canvasLayer!==hn.CanvasTemplate&&(l.visible===!1||l.calculative.visible===!1||this.store.animates.has(Uf(l,!0))&&(l.calculative.imageDrawed=!0,o.save(),SS(o,l),l.calculative.rotate&&vv(o,l),ES(o,l),J5(o,l),o.restore()));o.restore()}if(!this.isBottom&&!this.store.data.locked&&this.fitFlag){const o=(this.store.data.width||this.store.options.width)*this.store.data.scale,l=(this.store.data.height||this.store.options.height)*this.store.data.scale,c=this.store.data.origin.x+this.store.data.x||this.store.options.x||0,u=this.store.data.origin.y+this.store.data.y||this.store.options.y||0,h=this.fitOffscreen.getContext("2d");h.save(),h.clearRect(0,0,this.canvas.width,this.canvas.height),h.fillStyle="#ffffff66",h.strokeStyle=this.store.styles.activeColor,(a=this.store.data.fits)==null||a.forEach((d,f)=>{h.fillRect(c+o*d.x,u+l*d.y,o*d.width,l*d.height),d.active&&h.strokeRect(c+o*d.x,u+l*d.y,o*d.width,l*d.height)}),h.restore()}if(e||t||i&&this.isBottom||r&&!this.isBottom){const o=this.canvas.getContext("2d");o.clearRect(0,0,this.canvas.width,this.canvas.height),this.isBottom&&(this.store.patchFlagsBackground=!1),o.drawImage(this.offscreen,0,0,this.canvas.width,this.canvas.height),o.drawImage(this.animateOffsScreen,0,0,this.canvas.width,this.canvas.height),this.isBottom||(o.drawImage(this.otherOffsreen,0,0,this.canvas.width,this.canvas.height),this.store.patchFlagsTop=!1,!this.store.data.locked&&this.fitFlag&&o.drawImage(this.fitOffscreen,0,0,this.canvas.width,this.canvas.height))}}renderRule(e){var v,x,A,b,C,T,w,P;const{data:t,options:i}=this.store,{rule:r,ruleColor:n,scale:a,origin:o}=t;if(!(r??i.rule))return;const l=a*10;e.save();const c=n||i.ruleColor;e.strokeStyle=X$(c,.7);const u=o.x+t.x,h=o.y+t.y,{width:d,height:f}=this.canvas;let p=((v=i.ruleOptions)==null?void 0:v.height)||20;(x=i.ruleOptions)!=null&&x.background&&(e.beginPath(),e.fillStyle=(A=i.ruleOptions)==null?void 0:A.background,e.rect(0,0,d,p),e.fill(),e.rect(0,0,p,f),e.fill()),(b=i.ruleOptions)!=null&&b.underline&&(e.beginPath(),e.fillStyle=X$(c,.7),e.moveTo(0,p),e.lineTo(d,p),e.stroke(),e.moveTo(p,0),e.lineTo(p,f),e.stroke());let m=p/4;((C=i.ruleOptions)==null?void 0:C.baseline)==="bottom"&&(m=p*3/4),e.beginPath(),e.lineWidth=p/2,e.lineDashOffset=-u%l,e.setLineDash([1,l-1]),e.moveTo(0,m),e.lineTo(d,m),e.stroke(),e.beginPath(),e.lineDashOffset=-h%l,e.moveTo(m,0),e.lineTo(m,f),e.stroke(),e.strokeStyle=c,e.beginPath(),e.lineWidth=p,e.lineDashOffset=-u%(l*10),e.setLineDash([1,l*10-1]),e.moveTo(0,p/2),e.lineTo(d,p/2),e.stroke(),e.beginPath(),e.lineDashOffset=-h%(l*10),e.moveTo(p/2,0),e.lineTo(p/2,f),e.stroke(),e.beginPath(),e.fillStyle=((T=i.ruleOptions)==null?void 0:T.textColor)||e.strokeStyle;let g=0-Math.floor(u/l/10)*100,_=((w=i.ruleOptions)==null?void 0:w.textTop)||16,y=((P=i.ruleOptions)==null?void 0:P.textLeft)||4;u<0&&(g-=100);for(let M=u%(l*10);M{i.drawImage(l,r.x-e,r.y-e,this.magnifierSize,this.magnifierSize,0,0,this.magnifierSize,this.magnifierSize)}),i.restore(),i.beginPath();const a=i.createRadialGradient(e,e,e-5,e,e,e);a.addColorStop(0,"rgba(0,0,0,0.2)"),a.addColorStop(.8,"rgb(200,200,200)"),a.addColorStop(.9,"rgb(200,200,200)"),a.addColorStop(1,"rgba(200,200,200,0.9)"),i.strokeStyle=a,i.arc(e,e,e,0,Math.PI*2,!1),i.stroke(),i.restore(),this.offscreen.getContext("2d").drawImage(this.magnifierScreen,0,0,this.magnifierSize+5,this.magnifierSize+5,(r.x-e-2.5)/this.store.dpiRatio,(r.y-e-2.5)/this.store.dpiRatio,(this.magnifierSize+5)/this.store.dpiRatio,(this.magnifierSize+5)/this.store.dpiRatio)}updateDomOffscreen(){const e=this.domOffscreen.getContext("2d");e.clearRect(0,0,this.domOffscreen.width,this.domOffscreen.height);for(const t of this.store.data.pens)if((t.externElement||t.name==="gif")&&t.calculative.img){e.save(),e.translate(this.store.data.x,this.store.data.y);const{x:i,y:r,width:n,height:a}=t.calculative.worldRect;e.drawImage(t.calculative.img,i,r,n,a),e.restore()}}render(){this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.renderMagnifier();const e=this.canvas.getContext("2d");e.clearRect(0,0,this.canvas.width,this.canvas.height),e.drawImage(this.offscreen,0,0,this.canvas.width,this.canvas.height)}}function rFe(s){if(s.data.locked)throw new Error("canvas is locked")}class v0t{constructor(e,t){ke(this,"box");ke(this,"iframe");ke(this,"dialog");ke(this,"close");ke(this,"title");ke(this,"body");ke(this,"x");ke(this,"y");ke(this,"url");ke(this,"meta2dDiv");ke(this,"dialogMeta2d");ke(this,"store");this.parentElement=e,this.store=t,this.box=document.createElement("div"),this.dialog=document.createElement("div");let i=document.createElement("div");this.title=document.createElement("div"),this.close=document.createElement("span"),this.close.innerHTML=` `,this.body=document.createElement("div"),this.iframe=document.createElement("iframe"),this.iframe.setAttribute("frameborder","0"),this.meta2dDiv=document.createElement("div"),this.box.className="meta2d-dialog_mask",this.dialog.className="meta2d-dialog",this.body.className="meta2d-dialog_body",i.className="meta2d-dialog_header",this.title.className="meta2d-dialog-content",this.close.className="meta2d-dialog-close",this.meta2dDiv.className="meta2d-dialog-meta2d",i.appendChild(this.title),i.appendChild(this.close),this.body.appendChild(this.iframe),this.body.appendChild(this.meta2dDiv),this.dialog.appendChild(i),this.dialog.appendChild(this.body),this.box.appendChild(this.dialog),e.appendChild(this.box),this.dialog.onclick=n=>{n.stopPropagation()},this.box.onclick=()=>{this.hide()},this.close.onclick=()=>{this.hide()};let r;for(let n=0;n{this.iframe.contentWindow.meta2d&&(clearInterval(o),setTimeout(()=>{this.iframe.contentWindow.postMessage(JSON.stringify({name:"dialog",data:r}),"*")},100)),a++,a>50&&clearInterval(o)},300)}if((!this.dialogMeta2d||n)&&(this.box.style.display="block"),!n){this.meta2dDiv.style.display="block",this.dialogMeta2d||(globalThis.mainMeta2d=globalThis.meta2d,this.dialogMeta2d=new oFe(this.meta2dDiv),globalThis.meta2d=globalThis.mainMeta2d);const a=await MNe(this.store,t);a&&(this.box.style.display="block",this.dialogMeta2d.clear(!0),this.dialogMeta2d.open(a,!1),this.dialogMeta2d.lock(1),this.dialogMeta2d.resize(),this.dialogMeta2d.fitView(!0,0),this.dialogMeta2d.render(!0))}}hide(){this.box.style.display="none"}isUrl(e){return!!(e.startsWith("http")||e.includes("?")||e.includes("/"))}destroy(){var e;this.dialog.onclick=void 0,this.box.onclick=void 0,this.close.onclick=void 0,(e=this.dialogMeta2d)==null||e.destroy(!0)}}class J${constructor(e){ke(this,"box");ke(this,"currentAnchor");this.parentElement=e,this.box=document.createElement("div"),this.box.className="meta2d-title",e.appendChild(this.box);let t;for(let i=0;i'},warning:{},error:{}};class A0t{constructor(e,t){ke(this,"box");ke(this,"text");ke(this,"arrowUp");ke(this,"arrowDown");ke(this,"icon");ke(this,"confirm");ke(this,"cancel");ke(this,"x");ke(this,"y");this.parentElement=e,this.store=t,this.box=document.createElement("div"),this.text=document.createElement("div"),this.arrowUp=document.createElement("div"),this.arrowDown=document.createElement("div"),this.icon=document.createElement("div"),this.confirm=document.createElement("button"),this.cancel=document.createElement("button"),this.box.className="meta2d-popconfirm",this.text.className="text",this.arrowUp.className="arrow",this.arrowDown.className="arrow down",this.icon.className="icon",this.confirm.className="confirm",this.cancel.className="cancel",this.confirm.innerHTML="确定",this.cancel.innerHTML="取消",this.icon.innerHTML=x0t.info.icon,this.box.appendChild(this.text),this.box.appendChild(this.arrowUp),this.box.appendChild(this.arrowDown),this.box.appendChild(this.confirm),this.box.appendChild(this.cancel),this.box.appendChild(this.icon),e.appendChild(this.box);let i;for(let r=0;r0?(this.arrowUp.style.borderBottomColor="transparent",this.arrowDown.style.borderTopColor="#fff",a-=10):(a+=i.height+r.height+5,a+=10,this.arrowUp.style.borderBottomColor="#fff",this.arrowDown.style.borderTopColor="transparent"),this.x=n,this.y=a,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px"}hide(){this.x=-9999,this.box.style.left="-9999px"}showModal(e,t,i){return new Promise(r=>{this.text.innerHTML=i||"确认执行操作吗?",this.show(e,t),this.confirm.onclick=()=>{r(!0),this.hide()},this.cancel.onclick=()=>{r(!1),this.hide()}})}destroy(){this.box=null}}const Td="-moving";class yEe{constructor(e,t,i){ke(this,"canvas",document.createElement("canvas"));ke(this,"offscreen",G1());ke(this,"width");ke(this,"height");ke(this,"externalElements",document.createElement("div"));ke(this,"clientRect");ke(this,"canvasRect");ke(this,"activeRect");ke(this,"initActiveRect");ke(this,"dragRect");ke(this,"lastRotate",0);ke(this,"sizeCPs");ke(this,"activeInitPos");ke(this,"hoverType",pr.None);ke(this,"resizeIndex",0);ke(this,"mouseDown");ke(this,"hotkeyType");ke(this,"mouseRight");ke(this,"addCaches");ke(this,"touchCenter");ke(this,"initTouchDis");ke(this,"initScale");ke(this,"touchScaling");ke(this,"touchMoving");ke(this,"startTouches");ke(this,"lastOffsetX",0);ke(this,"lastOffsetY",0);ke(this,"drawingLineName");ke(this,"drawLineFns",[...Xdt]);ke(this,"drawingLine");ke(this,"pencil");ke(this,"pencilLine");ke(this,"movingPens");ke(this,"patchFlagsLines",new Set);ke(this,"dock");ke(this,"prevAnchor");ke(this,"nextAnchor");ke(this,"lastMouseTime",0);ke(this,"hoverTimer",0);ke(this,"fitTimer",0);ke(this,"willInactivePen");ke(this,"patchFlags",!1);ke(this,"lastRender",0);ke(this,"touchStart",0);ke(this,"touchStartTimer");ke(this,"timer");ke(this,"lastAnimateRender",0);ke(this,"animateRendering",!1);ke(this,"renderTimer");ke(this,"initPens");ke(this,"pointSize",8);ke(this,"pasteOffset",!0);ke(this,"opening",!1);ke(this,"maxZindex",5);ke(this,"canMoveLine",!1);ke(this,"randomIdObj");ke(this,"keyOptions");ke(this,"beforeAddPen");ke(this,"beforeAddPens");ke(this,"beforeAddAnchor");ke(this,"beforeRemovePens");ke(this,"beforeRemoveAnchor");ke(this,"customResizeDock");ke(this,"customMoveDock");ke(this,"inputParent",document.createElement("div"));ke(this,"inputDiv",document.createElement("div"));ke(this,"dropdown",document.createElement("ul"));ke(this,"tooltip");ke(this,"popconfirm");ke(this,"title");ke(this,"mousePos",{x:0,y:0});ke(this,"scroll");ke(this,"movingAnchor");ke(this,"canvasTemplate");ke(this,"canvasImage");ke(this,"canvasImageBottom");ke(this,"magnifierCanvas");ke(this,"dialog");ke(this,"autoPolylineFlag",!1);ke(this,"stopPropagation",e=>{e.stopPropagation()});ke(this,"curve",Wpt);ke(this,"polyline",Zpt);ke(this,"mind",Hpt);ke(this,"line",Xpt);ke(this,"onCopy",e=>{this.store.options.disableClipboard||e.target!==this.externalElements&&e.target!==document.body&&e.target.offsetParent!==this.externalElements||this.copy()});ke(this,"onCut",e=>{this.store.options.disableClipboard||e.target!==this.externalElements&&e.target!==document.body&&e.target.offsetParent!==this.externalElements||this.cut()});ke(this,"onPaste",async e=>{if(this.store.data.locked||this.store.options.disableClipboard||e.target!==this.externalElements&&e.target!==document.body&&e.target.offsetParent!==this.externalElements)return;let t;if(navigator.clipboard&&e.clipboardData){const i=e.clipboardData.items;if(i){for(let r=0;r{if(typeof e.data!="string"||!e.data||e.data.startsWith("setImmediate"))return;let t=JSON.parse(e.data);typeof t=="object"?this.parent.doMessageEvent(t.name,JSON.stringify(t.data)):this.parent.doMessageEvent(t)});ke(this,"onwheel",e=>{if(this.inputDiv.contentEditable==="true"||this.drawingLine||this.pencil)return;if(this.store.hover&&this.store.hover.onWheel){this.store.hover.onWheel(this.store.hover,e);return}if(this.store.data.disableScale||this.store.options.disableScale||(e.preventDefault(),e.stopPropagation(),this.mouseDown&&(this.hoverType===pr.Node||this.hoverType===pr.Line))||this.store.data.locked===qs.Disable||this.store.data.locked===qs.DisableScale||this.store.data.locked===qs.DisableMoveScale)return;if(!e.ctrlKey&&Math.abs(e.wheelDelta)<100&&e.deltaY.toString().indexOf(".")===-1){if(this.store.options.scroll&&!e.metaKey&&this.scroll){this.scroll.wheel(e.deltaY<0);return}const n=this.store.data.scale||1;this.translate(-e.deltaX/n,-e.deltaY/n);return}if(Math.abs(e.wheelDelta)>100&&this.store.options.scroll&&this.scroll&&!this.store.options.scrollButScale&&!(e.ctrlKey||e.metaKey)){this.scroll.wheel(e.deltaY<0);return}if(this.store.options.disableTouchPadScale)return;let t=.015;if(this.store.options.scaleOff)t=this.store.options.scaleOff,e.deltaY>0&&(t=-this.store.options.scaleOff);else if(/mac os /i.test(navigator.userAgent))e.ctrlKey?e.deltaY>0&&(t*=-1):t*=e.wheelDeltaY/240;else{let a=.2;e.deltaY.toString().indexOf(".")!==-1&&(a=.01),e.deltaY>0?t=-a:t=a}let{offsetX:i,offsetY:r}=e;this.scale(this.store.data.scale+t,{x:i,y:r}),this.externalElements.focus()});ke(this,"onkeydown",e=>{var n,a,o;if(this.store.data.locked>=qs.DisableEdit&&e.target.tagName!=="INPUT"&&e.target.tagName!=="TEXTAREA"&&!e.target.dataset.meta2dIgnore&&this.store.active.forEach(l=>{var c;(c=l.onKeyDown)==null||c.call(l,l,e.key)}),this.store.data.locked>=qs.DisableEdit||e.target.tagName==="INPUT"||e.target.tagName==="TEXTAREA"||e.target.dataset.meta2dIgnore||this.store.options.unavailableKeys.includes(e.key))return;this.keyOptions||(this.keyOptions={}),this.keyOptions.altKey=e.altKey,this.keyOptions.shiftKey=e.shiftKey,this.keyOptions.ctrlKey=e.ctrlKey,this.keyOptions.metaKey=e.metaKey,this.keyOptions.F=!1,(e.key==="F"||e.key==="f")&&(this.keyOptions.F=!0);let t=10,i=10,r=null;if(this.store.options.strictScope){const l=this.store.data.width||this.store.options.width,c=this.store.data.height||this.store.options.height;l&&c&&(r={x:this.store.data.origin.x,y:this.store.data.origin.y,width:l*this.store.data.scale,height:c*this.store.data.scale})}switch(e.key){case" ":this.hotkeyType=ia.Translate;break;case"Control":this.drawingLine?this.drawingLine.calculative.drawlineH=!this.drawingLine.calculative.drawlineH:this.hotkeyType||(this.patchFlags=!0,this.hotkeyType=ia.Select);break;case"Meta":break;case"Shift":this.store.active.length===1&&this.store.active[0].type&&this.store.activeAnchor?this.toggleAnchorHand():this.hotkeyType||(this.patchFlags=!0,this.store.options.resizeMode||(this.hotkeyType=ia.Resize));break;case"Alt":if(!e.ctrlKey&&!e.shiftKey&&this.drawingLine){const l=Dn(this.drawingLine);l!==this.drawingLine.calculative.activeAnchor?(Vme(this.drawingLine),this.drawingLine.calculative.worldAnchors.push(l)):this.drawingLine.calculative.worldAnchors.push({x:l.x,y:l.y});const c=this.drawLineFns.indexOf(this.drawingLineName);this.drawingLineName=this.drawLineFns[(c+1)%this.drawLineFns.length],this.drawingLine.lineName=this.drawingLineName,this.drawline(),this.patchFlags=!0}e.preventDefault();break;case"a":case"A":e.ctrlKey||e.metaKey?(this.active(this.store.data.pens.filter(l=>!l.parentId&&l.locked!==qs.Disable)),e.preventDefault()):this.toggleAnchorMode();break;case"Delete":case"Backspace":if(this.canvasImage.fitFlag&&this.canvasImage.activeFit){this.deleteFit();break}!this.store.data.locked&&this.delete();break;case"ArrowLeft":if(this.movingAnchor){this.translateAnchor(-1,0);break}if(t=-1,e.shiftKey&&(t=-5),(e.ctrlKey||e.metaKey)&&(t=-10),t=t*this.store.data.scale,this.store.activeAnchor&&this.store.active&&this.store.active.length===1&&this.store.active[0].type){this.moveLineAnchor({x:this.store.activeAnchor.x+t,y:this.store.activeAnchor.y},{});break}r&&this.activeRect.x+tr.x+r.width&&(t=r.x+r.width-(this.activeRect.x+this.activeRect.width)),this.translatePens(this.store.active,t,0);break;case"ArrowDown":if(this.movingAnchor){this.translateAnchor(0,1);break}if(i=1,e.shiftKey&&(i=5),(e.ctrlKey||e.metaKey)&&(i=10),i=i*this.store.data.scale,r&&this.activeRect.y+this.activeRect.height+i>r.y+r.height&&(i=r.y+r.height-(this.activeRect.y+this.activeRect.height)),this.store.activeAnchor&&this.store.active&&this.store.active.length===1&&this.store.active[0].type){this.moveLineAnchor({x:this.store.activeAnchor.x,y:this.store.activeAnchor.y+i},{});break}this.translatePens(this.store.active,0,i);break;case"d":case"D":(n=this.store.active[0])!=null&&n.locked||this.removeAnchorHand();break;case"h":case"H":(a=this.store.active[0])!=null&&a.locked||this.addAnchorHand();break;case"m":case"M":this.toggleMagnifier();break;case"g":case"G":this.hoverType===pr.NodeAnchor&&(this.movingAnchor=this.store.hoverAnchor,this.externalElements.style.cursor="move");break;case"s":case"S":!this.store.data.locked&&this.hoverType===pr.LineAnchor&&this.store.hover===this.store.active[0]&&this.splitLine(this.store.active[0],this.store.hoverAnchor),(e.ctrlKey||e.metaKey)&&this.store.emitter.emit("save",{event:e});break;case"c":case"C":(e.ctrlKey||e.metaKey)&&this.store.options.disableClipboard&&this.copy();break;case"x":case"X":(e.ctrlKey||e.metaKey)&&this.store.options.disableClipboard&&this.cut();break;case"√":case"v":case"V":!e.ctrlKey&&!e.metaKey&&(this.pencil&&this.stopPencil(),this.drawingLineName?(this.finishDrawline(),this.drawingLineName=""):this.drawingLineName=this.store.options.drawingLineName),!this.store.data.locked&&(e.ctrlKey||e.metaKey)&&(this.store.options.disableClipboard||!this.store.options.disableClipboard&&e.altKey)&&this.paste();break;case"b":case"B":this.drawingLineName&&(this.finishDrawline(),this.drawingLineName=""),this.pencil?this.stopPencil():this.drawingPencil();break;case"y":case"Y":(e.ctrlKey||e.metaKey)&&this.redo();break;case"z":case"Z":e.ctrlKey||e.metaKey?this.undo():e.shiftKey&&this.redo();break;case"Enter":this.drawingLineName&&(this.finishDrawline(!0),this.store.active[0].anchors[0].connectTo?this.drawingLineName="":this.drawingLineName=this.store.options.drawingLineName),this.store.active&&(this.store.active.forEach(l=>{l.type?(l.close=!l.close,l.close&&QNe(l),this.store.path2dMap.set(l,Lr.path2dDraws.line(l)),sue(l)):l.calculative.focus=!0}),this.render());break;case"Escape":this.drawingLineName&&this.finishDrawline(),this.drawingLineName=void 0,this.stopPencil(),this.store.active&&this.store.active.forEach(l=>{l.type||(l.calculative.focus=!1)}),this.movingPens&&(this.getAllByPens(this.movingPens).forEach(l=>{this.store.pens[l.id]=void 0}),this.movingPens=void 0,this.mouseDown=void 0,this.clearDock(),(o=this.store.active)==null||o.forEach(l=>{this.updateLines(l)}),this.calcActiveRect(),this.patchFlags=!0),this.hotkeyType=ia.None,this.movingAnchor=void 0,this.magnifierCanvas.magnifier&&(this.magnifierCanvas.magnifier=!1,this.patchFlags=!0);break;case"E":case"e":this.store.options.disableAnchor=!this.store.options.disableAnchor,this.store.emitter.emit("disableAnchor",this.store.options.disableAnchor);break;case"=":(e.ctrlKey||e.metaKey)&&(this.scale(this.store.data.scale+.1),e.preventDefault(),e.stopPropagation());break;case"-":(e.ctrlKey||e.metaKey)&&(this.scale(this.store.data.scale-.1),e.preventDefault(),e.stopPropagation());break;case"l":case"L":this.canMoveLine=!0;break;case"[":this.parent.down();break;case"]":this.parent.up();break;case"{":this.parent.bottom();break;case"}":this.parent.top();break;case"F":case"f":!this.store.data.locked&&(e.ctrlKey||e.metaKey)&&!this.store.options.disableClipboard&&this.paste(),this.setFollowers();break}this.render(!1)});ke(this,"onkeyup",e=>{switch(e.key){case"l":case"L":this.canMoveLine=!1;break}this.hotkeyType&&this.render(),this.hotkeyType{if(this.store.data.locked){console.warn("canvas is locked, can not drop");return}e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("Meta2d")||e.dataTransfer.getData("Text");let i=null;try{t&&(i=JSON.parse(t))}catch{}if(!i){const{files:r}=e.dataTransfer;if(r.length&&r[0].type.match("image.*")&&!(this.addCaches&&this.addCaches.length)){const n=r[0].type==="image/gif";i=await this.fileToPen(r[0],n)}else if(this.addCaches&&this.addCaches.length)i=this.addCaches,this.addCaches=[];else{this.store.emitter.emit("drop",void 0);return}}if(i=Array.isArray(i)?i:[i],i[0]&&i[0].draggable!==!1){const r={x:e.offsetX,y:e.offsetY};this.calibrateMouse(r),this.dropPens(i,r),this.addCaches=[],this.getContainerHover(r),this.mousePos.x=r.x,this.mousePos.y=r.y,this.store.emitter.emit("mouseup",{x:r.x,y:r.y,pen:this.store.hoverContainer})}this.store.emitter.emit("drop",i||t)});ke(this,"ontouchstart",e=>{this.store.data.locked!==qs.Disable&&(this.touchStartTimer&&clearTimeout(this.touchStartTimer),this.touchStartTimer=setTimeout(()=>{this.touchStart=performance.now();const t=e.touches[0].pageX-this.clientRect.x,i=e.touches[0].pageY-this.clientRect.y,r={x:t,y:i};if(this.calibrateMouse(r),this.getHover(r),this.onMouseDown({x:t,y:i,clientX:e.touches[0].clientX,clientY:e.touches[0].clientY,pageX:e.touches[0].pageX,pageY:e.touches[0].pageY,ctrlKey:e.ctrlKey||e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,buttons:1}),e.touches.length===2){this.initTouchDis=Math.hypot(e.touches[0].pageX-e.touches[1].pageX,e.touches[0].pageY-e.touches[1].pageY),this.initScale=this.store.data.scale,this.startTouches=e.touches,this.touchCenter={x:e.touches[0].pageX+(e.touches[1].pageX-e.touches[0].pageX)/2-this.clientRect.x,y:e.touches[0].pageY+(e.touches[1].pageY-e.touches[0].pageY)/2-this.clientRect.y};return}else e.touches.length===3&&(this.store.emitter.emit("contextmenu",{e:{x:t,y:i,clientX:e.touches[0].clientX,clientY:e.touches[0].clientY,pageX:e.touches[0].pageX,pageY:e.touches[0].pageY},clientRect:this.clientRect}),e.preventDefault(),e.stopPropagation());this.touchStartTimer=void 0},50))});ke(this,"ontouchmove",e=>{var o;if(this.store.data.locked===qs.Disable)return;e.stopPropagation(),e.preventDefault();const t=performance.now();if(t-this.touchStart<50)return;this.touchStart=t;const i=e.touches,r=i.length,n=e.touches[0].pageX-this.clientRect.x,a=e.touches[0].pageY-this.clientRect.y;if(r===1)this.onMouseMove({x:n,y:a,clientX:e.changedTouches[0].clientX,clientY:e.changedTouches[0].clientY,pageX:e.changedTouches[0].pageX,pageY:e.changedTouches[0].pageY,ctrlKey:e.ctrlKey||e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,buttons:1});else if(r===2&&((o=this.startTouches)==null?void 0:o.length)===2){if(!this.touchMoving&&!this.touchScaling){const l=this.startTouches[0].pageX-i[0].pageX,c=this.startTouches[1].pageX-i[1].pageX,u=this.startTouches[0].pageY-i[0].pageY,h=this.startTouches[1].pageY-i[1].pageY;(l>=0&&c<0||l<=0&&c>0)&&(u>=0&&h<0||u<=0&&h>0)?this.touchScaling=!0:this.touchMoving=!0}if(this.touchScaling){if(this.store.data.disableScale||this.store.options.disableScale)return;const l=Math.hypot(i[0].pageX-i[1].pageX,i[0].pageY-i[1].pageY)/this.initTouchDis;this.scale(this.initScale*l,bt(this.touchCenter))}if(this.touchMoving){if(this.store.data.locked>=qs.DisableMove&&this.store.data.locked!==qs.DisableScale||this.store.data.disableScale||this.store.options.disableScale)return;if(this.lastOffsetX){const{scale:l}=this.store.data;this.translate((n-this.lastOffsetX)/l,(a-this.lastOffsetY)/l)}this.lastOffsetX=n,this.lastOffsetY=a}}});ke(this,"ontouchend",e=>{if(this.store.data.locked===qs.Disable)return;this.touchCenter=void 0,this.touchScaling=void 0,this.touchMoving=void 0,this.startTouches=void 0,this.lastOffsetX=0,this.lastOffsetY=0;const t=e.changedTouches[0].pageX-this.clientRect.x,i=e.changedTouches[0].pageY-this.clientRect.y;this.onMouseUp({x:t,y:i,clientX:e.changedTouches[0].clientX,clientY:e.changedTouches[0].clientY,pageX:e.changedTouches[0].pageX,pageY:e.changedTouches[0].pageY,ctrlKey:e.ctrlKey||e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,buttons:1}),setTimeout(()=>{this.render()},20)});ke(this,"onGesturestart",e=>{e.preventDefault()});ke(this,"onMouseDown",e=>{var t,i,r,n,a;if(e.buttons===2&&!this.drawingLine&&(this.mouseRight=gy.Down),this.hideInput(),this.popconfirm.hide(),this.store.data.locked===qs.Disable||e.buttons!==1&&e.buttons!==2){this.hoverType=pr.None;return}if(!this.magnifierCanvas.magnifier){if(this.calibrateMouse(e),this.mousePos.x=e.x,this.mousePos.y=e.y,this.mouseDown=e,this.lastMouseTime=performance.now(),this.canvasImage.fitFlag){this.canvasImage.currentFit||this.calcuActiveFit();return}if(this.hotkeyType===ia.AddAnchor){this.setAnchor(this.store.pointAt);return}if(!this.store.options.autoAnchor&&!this.drawingLine&&e.shiftKey&&e.ctrlKey&&e.altKey){this.setAnchor(this.store.pointAt),this.drawingLineName=this.store.options.drawingLineName;const o=this.store.activeAnchor;if(!o)return;const l={id:fs(),x:o.x,y:o.y};this.drawingLine=this.createDrawingLine(l);let c=rl(this.drawingLine);this.drawingLine.calculative.activeAnchor=c,Zc(this.store.hover,o,this.drawingLine,l),this.drawline();return}if(!(this.hotkeyType===ia.Translate||this.mouseRight===gy.Down&&!this.store.options.mouseRightActive)){if(this.drawingLine){if(this.store.hoverAnchor){const l=Dn(this.drawingLine);this.store.hoverAnchor.type===WC.Line?$X(l,this.store.hoverAnchor,this.store):(l.x=this.store.hoverAnchor.x,l.y=this.store.hoverAnchor.y),Zc(this.store.hover,this.store.hoverAnchor,this.drawingLine,l),this.drawline(),this.finishDrawline(!0);return}if(!this.store.options.autoAnchor&&e.shiftKey&&e.altKey&&e.ctrlKey){this.setAnchor(this.store.pointAt);const l=Dn(this.drawingLine),c=this.store.activeAnchor;if(!c)return;l.x=c.x,l.y=c.y,Zc(this.store.hover,c,this.drawingLine,l),this.drawline(),this.finishDrawline(!0);return}if(e.buttons===2||this.drawingLineName==="mind"&&((t=this.drawingLine)==null?void 0:t.calculative.worldAnchors.length)>1||this.store.options.drawingLineLength&&((i=this.drawingLine)==null?void 0:i.calculative.worldAnchors.length)>this.store.options.drawingLineLength){this.finishDrawline(!0),(r=this.store.active[0])!=null&&r.anchors[0].connectTo||this.store.active.length==0?this.drawingLineName="":this.drawingLineName=this.store.options.drawingLineName;return}if(this.store.options.autoAnchor&&this.hoverType===pr.Node){const l=Dn(this.drawingLine),c=R5(this.store.hover,e);l.x=c.x,l.y=c.y,this.drawingLine.autoTo=!0,Zc(this.store.hover,c,this.drawingLine,l),this.drawline(),this.finishDrawline(!0);return}const o=Dn(this.drawingLine);o.isTemp?(this.drawingLine.calculative.activeAnchor=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2],o.isTemp=void 0):(this.drawingLine.calculative.activeAnchor=o,this.drawingLine.calculative.worldAnchors.push({x:o.x,y:o.y,penId:o.penId})),this.drawingLine.calculative.drawlineH=void 0,this.drawingLineName!=="polyline"&&this.drawline()}if(this.drawingLineName){if(this.hoverType===pr.Node)if(this.store.options.autoAnchor){this.inactive(!0);const o=R5(this.store.hover,e);this.store.hoverAnchor=o;const l={id:fs(),x:o.x,y:o.y};this.drawingLine=this.createDrawingLine(l),this.drawingLine.autoFrom=!0,Zc(this.store.hover,o,this.drawingLine,l)}else this.inactive(),this.hoverType=pr.None;else if(this.hoverType===pr.NodeAnchor){this.drawingLineName=this.store.options.drawingLineName;const o={id:fs(),x:this.store.hoverAnchor.x,y:this.store.hoverAnchor.y};this.drawingLine=this.createDrawingLine(o),this.drawingLine.calculative.activeAnchor=o,Zc(this.store.hover,this.store.hoverAnchor,this.drawingLine,o)}else if(!this.drawingLine&&this.drawingLineName!=="curve"){this.inactive(!0);const o={id:fs(),x:e.x,y:e.y};this.drawingLine=this.createDrawingLine(o),this.drawingLine.calculative.activeAnchor=o}}else if(this.pencil){this.inactive(!0);const o=fs(),l={x:e.x,y:e.y,id:fs(),penId:o};this.pencilLine=this.getInitPencilLine(l)}else{switch(this.hoverType){case pr.None:(this.store.data.rule||this.store.options.rule)&&!this.store.options.disableRuleLine&&this.addRuleLine(e),this.store.options.resizeMode&&(this.hotkeyType=ia.None),this.inactive();break;case pr.Node:case pr.Line:if(this.store.hover){if((n=this.store.active)!=null&&n.length&&this.store.active.length===1&&this.store.hover.id===this.store.active[0].id){this.calcActiveRect();break}const o=Uf(this.store.hover,!0);let l=o||this.store.hover;o&&(o.container||(a=this.store.options.containerShapes)!=null&&a.includes(o.name))&&(l=this.store.hover),e.ctrlKey&&!e.shiftKey?(l.calculative.active?this.willInactivePen=l:this.store.active.length>0&&(l.calculative.active=!0,v5(l),this.store.active.push(l),this.store.emitter.emit("active",this.store.active)),this.patchFlags=!0):e.ctrlKey&&e.shiftKey&&this.store.hover.parentId?this.active([this.store.hover]):(!(this.activeRect&&vy({x:e.x,y:e.y},this.activeRect))||this.store.active.length==1)&&(l.calculative.active||(this.active([l]),this.store.options.resizeMode&&(this.hotkeyType=ia.Resize))),this.calcActiveRect()}break;case pr.LineAnchor:this.store.activeAnchor=this.store.hoverAnchor,this.store.hover.calculative.activeAnchor=this.store.hoverAnchor,this.active([this.store.hover]);break;case pr.LineAnchorPrev:case pr.LineAnchorNext:this.store.activeAnchor&&(this.prevAnchor={...this.store.activeAnchor.prev},this.nextAnchor={...this.store.activeAnchor.next});break;case pr.Resize:this.activeInitPos=[],this.store.active.forEach(o=>{this.activeInitPos.push({x:(o.calculative.worldRect.x-this.activeRect.x)/this.activeRect.width,y:(o.calculative.worldRect.y-this.activeRect.y)/this.activeRect.height})});break}this.store.hover&&(this.store.hover.calculative.mouseDown=!0),this.store.emitter.emit("mousedown",{x:e.x,y:e.y,pen:this.store.hover})}this.render()}}});ke(this,"onMouseMove",e=>{var i,r,n,a,o,l,c,u;if(this.store.data.locked===qs.Disable){this.hoverType=pr.None;return}if(this.mouseDown&&!this.mouseDown.restore&&e.buttons!==1&&e.buttons!==2){this.onMouseUp(e);return}if(this.lastMouseTime){if(performance.now()-this.lastMouseTime<50){this.lastMouseTime=0;return}this.lastMouseTime=0}if(this.calibrateMouse(e),this.mousePos.x=e.x,this.mousePos.y=e.y,this.magnifierCanvas.magnifier){this.render();return}if(this.canvasImage.fitFlag&&this.canvasImage.activeFit){const h=performance.now();h-this.fitTimer>100&&(this.mouseDown?this.updateFit(e):this.inFitBorder(this.mousePos),this.fitTimer=h);return}if(this.mouseDown&&!this.store.options.disableTranslate&&!this.store.data.disableTranslate){if(this.mouseRight===gy.Down&&(this.mouseRight=gy.Translate),this.store.data.locked===qs.DisableEdit||this.store.data.locked===qs.DisableScale||this.hotkeyType===ia.Translate||this.mouseRight===gy.Translate){const{scale:h}=this.store.data;let d=(e.x-this.mouseDown.x)/h,f=(e.y-this.mouseDown.y)/h;e.shiftKey&&!e.ctrlKey&&(f=0),e.ctrlKey&&(d=0),this.translate(d,f);return}if(this.store.data.locked)return;if(!this.drawingLine&&!this.pencil){if(!this.drawingLineName&&!this.movingAnchor){if(this.hoverType===pr.NodeAnchor){if(!this.store.hoverAnchor)return;this.drawingLineName=this.store.options.drawingLineName;const h={id:fs(),x:this.store.hoverAnchor.x,y:this.store.hoverAnchor.y};this.drawingLine=this.createDrawingLine(h),this.drawingLine.calculative.activeAnchor=h,Zc(this.store.hover,this.store.hoverAnchor,this.drawingLine,h),this.drawline();return}}else if(this.drawingLineName&&this.hoverType===pr.None){const h={id:fs(),x:e.x,y:e.y};this.drawingLine=this.createDrawingLine(h),this.drawingLine.calculative.activeAnchor=h,this.drawline();return}if(e.buttons===1&&(e.ctrlKey||!this.hoverType&&!this.hotkeyType)&&!(e.ctrlKey&&(this.store.activeAnchor||(i=this.store.active)!=null&&i.length))){this.dragRect={x:Math.min(this.mouseDown.x,e.x),y:Math.min(this.mouseDown.y,e.y),ex:Math.max(this.mouseDown.x,e.x),ey:Math.max(this.mouseDown.y,e.y),width:Math.abs(e.x-this.mouseDown.x),height:Math.abs(e.y-this.mouseDown.y)},this.render();return}if(this.movingAnchor){const h=e.x-this.movingAnchor.x,d=e.y-this.movingAnchor.y;this.translateAnchor(h,d),this.render();return}else if(!((r=this.store.active[0])!=null&&r.locked)){const h={x:e.x,y:e.y};if(this.hoverType===pr.LineAnchor){(this.dockInAnchor(e)||((n=this.store.active[0])==null?void 0:n.lineName)==="line")&&!this.store.options.disableDock&&!this.store.options.disableLineDock&&(this.clearDock(),this.dock=aEe(this.store,h,this.store.activeAnchor),(a=this.dock)!=null&&a.xDock&&(h.x+=this.dock.xDock.step),(o=this.dock)!=null&&o.yDock&&(h.y+=this.dock.yDock.step)),this.moveLineAnchor(h,e);return}if(this.hoverType===pr.LineAnchorPrev){this.moveLineAnchorPrev(e);return}if(this.hoverType===pr.LineAnchorNext){this.moveLineAnchorNext(e);return}}if(this.hoverType===pr.Rotate){this.rotatePens({x:e.x,y:e.y});return}if(this.hoverType===pr.Resize){this.resizePens(e);return}if(this.hoverType===pr.Node||this.hoverType===pr.Line){const h=e.x-this.mouseDown.x,d=e.y-this.mouseDown.y,f=20;if(e.ctrlKey&&!e.shiftKey&&(Math.abs(h)>=f||Math.abs(d)>=f)&&(this.willInactivePen=void 0),this.store.active.length===1){const p=this.store.active[0];if((p.locked===void 0||p.locked1&&(p=Dn(this.drawingLine)),p?(p.prev=void 0,p.next=void 0,p.id||(p.id=fs()),p.x=f.x,p.y=f.y,p.connectTo=void 0):(p={...f},this.drawingLine.calculative.worldAnchors.push(p)),(this.hoverType===pr.NodeAnchor||this.hoverType===pr.LineAnchor)&&(this.store.hoverAnchor.type!==WC.Line&&(p.x=this.store.hoverAnchor.x,p.y=this.store.hoverAnchor.y),p.connectTo=this.store.hoverAnchor.penId,this.drawingLineName==="polyline"&&(p.isTemp=!1)),this.drawingLineName==="line"){if(e.ctrlKey&&!e.shiftKey)p.x=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2].x;else if(e.shiftKey&&!e.ctrlKey)p.y=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2].y;else if(e.shiftKey&&e.ctrlKey){let m=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2];this.getSpecialAngle(p,m)}}this.drawline()}}globalThis.debug&&console.time("hover");const t=performance.now();t-this.hoverTimer>50&&(this.hoverTimer=t,this.getHover(e)),globalThis.debug&&console.timeEnd("hover"),this.hotkeyType===ia.AddAnchor&&(this.patchFlags=!0),this.render(!1)});ke(this,"onMouseUp",e=>{if(this.store.data.locked===qs.Disable){this.hoverType=pr.None;return}if(this.mouseDown){if(this.mouseRight===gy.Down&&(this.store.hover&&this.store.hover.onContextmenu?this.store.hover.onContextmenu(this.store.hover,e):this.store.emitter.emit("contextmenu",{e,clientRect:this.clientRect,pen:this.store.hover})),this.mouseRight=gy.None,this.calibrateMouse(e),this.mousePos.x=e.x,this.mousePos.y=e.y,this.pencil&&this.finishPencil(),this.drawingLine){if(this.store.hoverAnchor){const t=Dn(this.drawingLine);this.store.hoverAnchor.type===WC.Line?$X(t,this.store.hoverAnchor,this.store):(t.x=this.store.hoverAnchor.x,t.y=this.store.hoverAnchor.y),Zc(this.store.hover,this.store.hoverAnchor,this.drawingLine,t),this.drawline(),this.finishDrawline(!0);return}if(this.store.options.autoAnchor&&this.hoverType===pr.Node){const t=Dn(this.drawingLine),i=R5(this.store.hover,e);t.x=i.x,t.y=i.y,this.drawingLine.autoTo=!0,Zc(this.store.hover,i,this.drawingLine,t),this.drawline(),this.finishDrawline(!0);return}}if(this.hoverType===pr.LineAnchor&&this.store.hover&&this.store.active[0]&&this.store.active[0].name==="line"&&this.store.active[0]!==this.store.hover){const t=this.store.active[0],i=rl(t),r=Dn(t);if(this.store.hoverAnchor){const n=this.store.hover,a=rl(n)===this.store.hoverAnchor,o=Dn(n)===this.store.hoverAnchor,l=i===this.store.activeAnchor,c=r===this.store.activeAnchor;if((e.ctrlKey||e.altKey)&&n.type===Kn.Line&&(a||o)&&(l||c)){const u=n.calculative.worldAnchors.map(h=>({...h,penId:t.id}));a?u.shift():o&&u.pop(),(a&&l||o&&c)&&u.reverse(),l?(t.calculative.worldAnchors[0].connectTo=void 0,t.calculative.worldAnchors.unshift(...u)):c&&(t.calculative.worldAnchors[t.calculative.worldAnchors.length-1].connectTo=void 0,t.calculative.worldAnchors.push(...u)),this.delete([n]),this.render()}else this.store.activeAnchor&&(this.store.hoverAnchor.type===WC.Line?$X(this.store.activeAnchor,this.store.hoverAnchor,this.store):(this.store.activeAnchor.x=this.store.hoverAnchor.x,this.store.activeAnchor.y=this.store.hoverAnchor.y),Zc(this.store.hover,this.store.hoverAnchor,t,this.store.activeAnchor));this[t.lineName]&&t.lineName!=="polyline"&&this[t.lineName](this.store,t),this.store.path2dMap.set(t,Lr.path2dDraws.line(t)),this.initLineRect(t)}else i===this.store.activeAnchor&&t.autoFrom?this.calcAutoAnchor(t,i,this.store.hover):r===this.store.activeAnchor&&t.autoTo&&this.calcAutoAnchor(t,r,this.store.hover)}if(this.addCaches&&this.addCaches.length){if(!this.store.data.locked){if(this.dragRect&&this.addCaches.length===1){const t=this.addCaches[0];t.width=this.dragRect.width/this.store.data.scale,t.height=this.dragRect.height/this.store.data.scale,e.x=(this.dragRect.x+this.dragRect.ex)/2,e.y=(this.dragRect.y+this.dragRect.ey)/2}this.dropPens(this.addCaches,e)}this.addCaches=void 0}if(this.hoverType===pr.Rotate&&(this.getSizeCPs(),this.store.active.forEach(t=>{t.rotate=t.calculative.rotate})),this.patchFlagsLines.forEach(t=>{t.type&&this.initLineRect(t)}),this.patchFlagsLines.clear(),this.dragRect)if(this.canvasImage.fitFlag)this.makeFit();else{const t=this.store.data.pens.filter(i=>{if(i.visible===!1||i.locked>=qs.DisableMove||i.parentId||i.isRuleLine)return!1;if(ov(i.calculative.worldRect,this.dragRect,e.ctrlKey||this.store.options.dragAllIn))return i.type===Kn.Line&&!this.store.options.dragAllIn?Fse(i,this.dragRect):!0});this.active(t)}if(e.button!==2&&(_J(this.mouseDown,e)<2&&(this.store.hover&&this.store.hover.input&&(this.store.hover.onShowInput?this.store.hover.onShowInput(this.store.hover,e):this.showInput(this.store.hover)),this.store.emitter.emit("click",{x:e.x,y:e.y,pen:this.store.hover})),this.store.hover&&(this.store.hover.calculative.mouseDown=!1),this.store.hover!=this.store.hoverContainer&&this.store.emitter.emit("mouseup",{x:e.x,y:e.y,pen:this.store.hover}),this.store.emitter.emit("mouseup",{x:e.x,y:e.y,pen:this.store.hoverContainer})),this.willInactivePen){this.willInactivePen.calculative.active=void 0,v5(this.willInactivePen,!1);const t=this.store.active.findIndex(i=>i===this.willInactivePen);t>=0&&this.store.active.splice(t,1),this.calcActiveRect(),this.willInactivePen=void 0,this.store.emitter.emit("inactive",[this.willInactivePen]),this.render()}this.movingPens&&(e.altKey&&!e.shiftKey?this.copyMovedPens():this.movedActivePens(e.ctrlKey&&e.shiftKey),this.getAllByPens(this.movingPens).forEach(t=>{this.store.pens[t.id]=void 0}),this.movingPens=void 0),this.store.active&&this.store.active[0]&&(this.store.active[0].calculative.h=void 0),this.mouseDown=void 0,this.lastOffsetX=0,this.lastOffsetY=0,this.clearDock(),this.dragRect=void 0,this.initActiveRect=void 0,this.render()}});ke(this,"clearDock",()=>{var n,a,o,l;const e=(a=(n=this.dock)==null?void 0:n.xDock)==null?void 0:a.penId,t=(l=(o=this.dock)==null?void 0:o.yDock)==null?void 0:l.penId,i=this.store.pens[e];i&&(i.calculative.isDock=!1);const r=this.store.pens[t];r&&(r.calculative.isDock=!1),this.dock=void 0});ke(this,"onResize",()=>{this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.resize(),this.timer=void 0},100)});ke(this,"onScroll",()=>{this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.clientRect=this.canvas.getBoundingClientRect(),this.timer=void 0},100)});ke(this,"calibrateMouse",e=>(e.x-=this.store.data.x,e.y-=this.store.data.y,e));ke(this,"getContainerHover",e=>{var i;if(this.dragRect)return;this.store.hoverContainer=void 0;const t=this.store.data.pens.filter(r=>{var n;return r.container||((n=this.store.options.containerShapes)==null?void 0:n.includes(r.name))});if(t.length)for(let r=t.length-1;r>=0;--r){const n=t[r];if(!(n.visible==!1||n.calculative.inView==!1||n.locked===qs.Disable)){if(vy(e,n.calculative.worldRect))this.store.hoverContainer=n,(i=n==null?void 0:n.onMouseMove)==null||i.call(n,n,e),this.store.lastHoverContainer!==this.store.hoverContainer&&(this.patchFlags=!0,this.store.lastHoverContainer&&(this.store.lastHoverContainer.calculative.containerHover=!1,this.store.emitter.emit("leave",this.store.lastHoverContainer)),this.store.hoverContainer&&(this.store.hoverContainer.calculative.containerHover=!0,this.store.emitter.emit("enter",this.store.hoverContainer)),this.store.lastHoverContainer=this.store.hoverContainer);else if(n===this.store.hoverContainer&&(this.store.hoverContainer=void 0,this.store.lastHoverContainer!==this.store.hoverContainer)){this.patchFlags=!0;const a=this.store.lastHoverContainer.calculative.canvas.store.pens[this.store.lastHoverContainer.id+Td];this.store.lastHoverContainer&&!a&&(this.store.lastHoverContainer.calculative.containerHover=!1,this.store.emitter.emit("leave",this.store.lastHoverContainer)),this.store.lastHoverContainer=this.store.hoverContainer}}}});ke(this,"getHover",e=>{var r,n;if(this.dragRect||this.canvasImage.fitFlag)return;let t=pr.None;this.store.hover=void 0,this.store.hoverAnchor=void 0,this.title.hide(),this.store.pointAt=void 0,this.store.pointAtIndex=void 0;const i=this.store.active.length===1&&this.store.active[0].type;if(!this.drawingLineName&&this.hotkeyType!==ia.AddAnchor&&this.activeRect&&!i&&!this.store.data.locked){const a=Ose(this.store.active),o=rEe(this.store.active)||this.store.options.disableRotate,l=sEe(this.store.active)||this.store.options.disableSize;if(!a&&!o){const c={x:this.activeRect.center.x,y:this.activeRect.y-30};this.activeRect.rotate&&Pa(c,this.activeRect.rotate,this.activeRect.pivot||this.activeRect.center),!this.hotkeyType&&g5(e,c,this.pointSize)&&(t=pr.Rotate,this.externalElements.style.cursor=`url("${this.store.options.rotateCursor}"), auto`)}if(!a&&!l)for(let c=0;c<8;c++){const u=c<4;if((this.hotkeyType===ia.Resize||u&&!this.hotkeyType)&&g5(e,this.sizeCPs[c],this.pointSize)){let d=u?Y6e:Q6e,f=0;Math.abs(this.activeRect.rotate%90-45)<25?(d=u?Q6e:Y6e,f=Math.round((this.activeRect.rotate-45)/90)+(u?0:1)):f=Math.round(this.activeRect.rotate/90),t=pr.Resize,this.resizeIndex=c,this.externalElements.style.cursor=d[(c+f)%4];break}}}t===pr.None&&(t=this.inPens(e,this.store.data.pens)),!t&&!i&&vy(e,this.activeRect)&&(t=pr.Node,this.externalElements.style.cursor="move"),this.hoverType=t,t===pr.None&&(this.drawingLineName||this.pencil?this.externalElements.style.cursor="crosshair":this.mouseDown||(this.externalElements.style.cursor="default"),this.store.hover=void 0),this.store.lastHover!==this.store.hover&&(this.patchFlags=!0,this.store.lastHover&&(this.store.lastHover.calculative.hover=!1,pB(Uf(this.store.lastHover,!0)||this.store.lastHover,!1),this.store.emitter.emit("leave",this.store.lastHover),this.tooltip.hide()),this.store.hover&&(this.store.hover.calculative.hover=!0,pB(Uf(this.store.hover,!0)||this.store.hover),this.store.emitter.emit("enter",this.store.hover),this.tooltip.show(this.store.hover,e)),this.store.lastHover=this.store.hover),(n=(r=this.store.hover)==null?void 0:r.onMouseMove)==null||n.call(r,this.store.hover,this.mousePos)});ke(this,"inPens",(e,t)=>{var r;let i=pr.None;e:for(let n=t.length-1;n>=0;--n){const a=t[n];if(a.visible==!1||a.calculative.inView==!1||a.locked===qs.Disable)continue;const o=q$(a);if(!(!a.calculative.active&&!TS(e,a.calculative.worldRect,o)&&!vy(e,a.calculative.worldRect))){if(!this.store.data.locked&&this.hotkeyType!==ia.Resize&&a.calculative.worldAnchors){for(const l of a.calculative.worldAnchors)if(i=this.inAnchor(e,a,l),i){let c=bt(l);Object.assign(c,e),this.title.show(c,a);break e}}if(a.type){if(a.isRuleLine){let c=((r=this.store.options.ruleOptions)==null?void 0:r.height)||20;if(e.x+this.store.data.x>c&&e.y+this.store.data.y>c)break}const l=Ypt(e,a);if(l){!this.store.data.locked&&!a.locked?this.hotkeyType===ia.AddAnchor?this.externalElements.style.cursor="pointer":this.externalElements.style.cursor="move":this.externalElements.style.cursor=this.store.options.hoverCursor,a.calculative.disabled&&(this.externalElements.style.cursor="not-allowed"),this.store.hover=a,this.store.pointAt=l.point,this.store.pointAtIndex=l.i,this.initTemplateCanvas([this.store.hover]),i=pr.Line;break}}else{if(a.children){const c=[];if(a.children.forEach(u=>{this.store.pens[u]&&c.push(this.store.pens[u])}),i=this.inPens(e,c),i)break}let l=!1;if(a.name==="line"?l=TS(e,a.calculative.worldRect,a.lineWidth):l=vy(e,a.calculative.worldRect),l){if(a.type===Kn.Node&&a.name==="line"&&!mpt(e,a.calculative.worldAnchors))continue;if(!this.store.data.locked&&!a.locked?this.hotkeyType===ia.AddAnchor?this.externalElements.style.cursor="pointer":this.externalElements.style.cursor="move":this.externalElements.style.cursor=this.store.options.hoverCursor,a.calculative.disabled&&(this.externalElements.style.cursor="not-allowed"),this.store.hover=a,this.initTemplateCanvas([this.store.hover]),i=pr.Node,this.store.pointAt=e,!e.ctrlKey){let{x:c,y:u,ex:h,ey:d,rotate:f,center:p}=this.store.hover.calculative.worldRect;if(f){const m=[{x:c,y:u},{x:h,y:u},{x:h,y:d},{x:c,y:d}];m.forEach(_=>{Pa(_,f,p)});let g=m[m.length-1];for(const _ of m){if(g.y>e.y!=_.y>e.y){const y=_.x+(e.y-_.y)*(g.x-_.x)/(g.y-_.y);Math.abs(y-this.store.pointAt.x)<10&&(this.store.pointAt.x=y)}g=_}}else this.store.pointAt.x-10h&&(this.store.pointAt.x=h),this.store.pointAt.y-10d&&(this.store.pointAt.y=d)}break}}}}return i});ke(this,"dockInAnchor",e=>{var t,i;this.store.hover=void 0;for(let r=this.store.data.pens.length-1;r>=0;--r){const n=this.store.data.pens[r];if(n.visible==!1||n.locked===qs.Disable||n===this.store.active[0])continue;let a=q$(n);if(a+=2*this.store.options.anchorRadius,!!TS(e,n.calculative.worldRect,a)&&(this.store.hover=n,this.hotkeyType!==ia.Resize&&n.calculative.worldAnchors))for(const o of n.calculative.worldAnchors){if(o.twoWay===uh.In){const l=Dn(this.store.active[0]);if(this.store.activeAnchor.id!==l.id)continue}if(o.twoWay===uh.Out){const l=rl(this.store.active[0]);if(this.store.activeAnchor.id!==l.id)continue}if(!(o.twoWay===uh.DisableConnected||o.twoWay===uh.Disable||((t=this.store.activeAnchor)==null?void 0:t.twoWay)===uh.DisableConnectTo||((i=this.store.activeAnchor)==null?void 0:i.twoWay)===uh.Disable)&&(this.title.hide(),this.inAnchor(e,n,o))){let l=bt(o);return Object.assign(l,e),this.title.show(l,n),!0}}}});ke(this,"imageTimer");ke(this,"templateImageTimer");ke(this,"render",e=>{if(e&&(this.opening=!1),this.opening)return;let t;if(e==null||e===!0||e===1/0?(t=performance.now(),this.patchFlags=!0):e>1?t=e:t=performance.now(),!this.patchFlags)return;if(t-this.lastRender{const e=this.offscreen.getContext("2d");e.strokeStyle=this.store.styles.color;for(const t of this.store.data.pens)isFinite(t.x)&&t.canvasLayer!==hn.CanvasTemplate&&(t.name==="combine"&&!t.draw||t.calculative.inView&&(t.canvasLayer===hn.CanvasMain&&t.name!=="gif"&&t.image&&t.calculative.img&&(e.save(),SS(e,t),t.calculative.rotate&&vv(e,t),ES(e,t),J5(e,t),e.restore()),KC(e,t)));this.drawingLine&&KC(e,this.drawingLine),this.pencilLine&&KC(e,this.pencilLine),this.movingPens&&this.movingPens.forEach(t=>{this.renderPenContainChild(e,t)})});ke(this,"renderPenContainChild",(e,t)=>{var i;t.calculative.inView&&(t.name==="combine"&&!t.draw||KC(e,t)),(i=t.children)==null||i.forEach(r=>{const n=this.store.pens[r];n&&this.renderPenContainChild(e,n)})});ke(this,"renderBorder",()=>{if(!this.store.data.locked&&this.activeRect&&!(this.store.active.length===1&&this.store.active[0].type)&&!this.movingPens){const e=this.offscreen.getContext("2d");e.save(),e.translate(.5,.5);const t=this.activeRect.pivot||this.activeRect.center;if(this.activeRect.rotate&&(e.translate(t.x,t.y),e.rotate(this.activeRect.rotate*Math.PI/180),e.translate(-t.x,-t.y)),e.strokeStyle=this.store.styles.activeColor,e.globalAlpha=this.store.options.activeGlobalAlpha===void 0?.3:this.store.options.activeGlobalAlpha,e.beginPath(),e.lineWidth=this.store.options.activeLineWidth||1,e.setLineDash(this.store.options.activeLineDash||[]),e.strokeRect(this.activeRect.x,this.activeRect.y,this.activeRect.width,this.activeRect.height),e.setLineDash([]),e.lineWidth=1,e.globalAlpha=1,Ose(this.store.active)||rEe(this.store.active)||this.store.options.disableRotate){e.restore();return}e.beginPath(),e.moveTo(this.activeRect.center.x,this.activeRect.y),e.lineTo(this.activeRect.center.x,this.activeRect.y-30),e.stroke(),e.beginPath(),e.strokeStyle=this.store.styles.activeColor,e.fillStyle="#ffffff",e.arc(this.activeRect.center.x,this.activeRect.y-30,5,0,Math.PI*2),e.fill(),e.stroke(),e.restore()}});ke(this,"renderHoverPoint",()=>{if(this.store.data.locked)return;const e=this.offscreen.getContext("2d");if(e.save(),e.translate(.5,.5),!this.store.options.disableAnchor&&this.store.hover&&!this.store.hover.disableAnchor&&(this.hotkeyType!==ia.Resize||this.store.active.length!==1||this.store.active[0]!==this.store.hover)){const t=[...this.store.hover.calculative.worldAnchors];this.store.pointAt&&this.hotkeyType===ia.AddAnchor&&t.push(this.store.pointAt),t&&(e.strokeStyle=this.store.hover.anchorColor||this.store.styles.anchorColor,e.fillStyle=this.store.hover.anchorBackground||this.store.options.anchorBackground,t.forEach(i=>{if(i.hidden&&i.locked>qs.DisableEdit)return;if(i===this.store.hoverAnchor){e.save();const n=this.store.hover.hoverAnchorColor||this.store.options.hoverAnchorColor;e.strokeStyle=n,e.fillStyle=n}e.beginPath();let r=i.radius||this.store.hover.anchorRadius||this.store.options.anchorRadius;if(this.store.hover.type&&!i.radius&&!this.store.hover.anchorRadius&&(r=3,this.store.hover.calculative.lineWidth>3&&(r=this.store.hover.calculative.lineWidth)),i.type===WC.Line){let n=this.store.pens[i.penId].rotate||0;this.store.pens[i.penId].calculative.flipX&&(n*=-1),this.store.pens[i.penId].calculative.flipY&&(n*=-1);let a=i.rotate+n;this.store.pens[i.penId].calculative.flipX&&(a*=-1),this.store.pens[i.penId].calculative.flipY&&(a*=-1),e.save(),e.translate(i.x,i.y),e.rotate(a*Math.PI/180),e.translate(-i.x,-i.y),e.rect(i.x-i.length*this.store.data.scale/2,i.y-r,i.length*this.store.data.scale,r*2),e.restore()}else e.arc(i.x,i.y,r,0,Math.PI*2);if(this.store.hover.type&&this.store.hoverAnchor===i?(e.save(),e.strokeStyle=this.store.hover.activeColor||this.store.styles.activeColor,e.fillStyle=e.strokeStyle):(i.color||i.background)&&(e.save(),e.strokeStyle=i.color,e.fillStyle=i.background),e.fill(),e.stroke(),i===this.store.hoverAnchor&&e.restore(),(this.store.hover.type&&this.store.hoverAnchor===i||i.color||i.background)&&e.restore(),!this.store.hover.parentId&&this.store.hover.children&&this.store.hover.children.length>0&&i===this.store.hoverAnchor){e.save(),e.beginPath(),e.lineWidth=3;const n=this.store.hover.hoverAnchorColor||this.store.options.hoverAnchorColor;globalThis.pSBC&&(e.strokeStyle=globalThis.pSBC(.5,n)),e.arc(i.x,i.y,r+1.5,0,Math.PI*2),e.stroke(),e.restore()}}))}this.hotkeyType!==ia.AddAnchor&&!this.movingPens&&this.activeRect&&!(this.store.active.length===1&&this.store.active[0].type)&&!Ose(this.store.active)&&!sEe(this.store.active)&&!this.store.options.disableSize&&(e.strokeStyle=this.store.styles.activeColor,e.fillStyle="#ffffff",this.sizeCPs.forEach((t,i)=>{this.activeRect.rotate&&(e.save(),e.translate(t.x,t.y),e.rotate(this.activeRect.rotate*Math.PI/180),e.translate(-t.x,-t.y)),(i<4||this.hotkeyType===ia.Resize)&&(e.beginPath(),e.fillRect(t.x-4.5,t.y-4.5,8,8),e.strokeRect(t.x-5.5,t.y-5.5,10,10)),this.activeRect.rotate&&e.restore()})),!this.store.data.locked&&this.dragRect&&(e.save(),e.fillStyle=X$(this.store.options.dragColor,.2),e.strokeStyle=this.store.options.dragColor,e.beginPath(),e.strokeRect(this.dragRect.x,this.dragRect.y,this.dragRect.width,this.dragRect.height),e.fillRect(this.dragRect.x,this.dragRect.y,this.dragRect.width,this.dragRect.height),e.restore()),this.dock&&(e.strokeStyle=this.store.options.dockColor,this.dock.xDock&&(e.beginPath(),e.moveTo(this.dock.xDock.x,this.dock.xDock.y),e.lineTo(this.dock.xDock.x,this.dock.xDock.prev.y),e.stroke()),this.dock.yDock&&(e.beginPath(),e.moveTo(this.dock.yDock.x,this.dock.yDock.y),e.lineTo(this.dock.yDock.prev.x,this.dock.yDock.y),e.stroke())),e.restore()});ke(this,"transTimeout");ke(this,"pastePen",(e,t)=>{const i=e.id;if(oEe(e),e.parentId=t,e.type===Kn.Line?this.changeNodeConnectedLine(i,e,this.store.clipboard.pens):this.changeLineAnchors(i,e,this.store.clipboard.pens),!e.parentId){const n=this.getPenRect(e,this.store.clipboard.origin,this.store.clipboard.scale),a=this.getPenRect(this.store.clipboard.initRect,this.store.clipboard.origin,this.store.clipboard.scale),{origin:o,scale:l}=this.store.data;e.x=o.x+n.x*l,e.y=o.y+n.y*l,e.width=n.width*l,e.height=n.height*l,a.x=o.x+a.x*l,a.y=o.y+a.y*l,ro(a),this.store.clipboard.pos&&(e.x-=a.center.x-this.store.clipboard.pos.x,e.y-=a.center.y-this.store.clipboard.pos.y),this.keyOptions&&this.keyOptions.altKey&&(this.keyOptions.ctrlKey||this.keyOptions.metaKey)?(e.x=-this.store.data.x+this.width/2-e.width/2,e.y=-this.store.data.y+this.height/2-e.height/2):this.keyOptions&&this.keyOptions.shiftKey&&(this.keyOptions.ctrlKey||this.keyOptions.metaKey||this.keyOptions.F)||(e.x+=this.store.clipboard.offset*this.store.data.scale,e.y+=this.store.clipboard.offset*this.store.data.scale)}this.makePen(e);const r=[];if(Array.isArray(e.children))for(const n of e.children){const a=this.store.clipboard.pens.find(o=>o.id===n);a&&r.push(this.pastePen(a,e.id).id)}return e.children=r,sv(e,!0),e});ke(this,"ondblclick",e=>{var t;this.store.hover&&(!this.store.data.locked||this.store.hover.dbInput)&&!this.store.options.disableInput&&(this.store.hover.onShowInput?this.store.hover.onShowInput(this.store.hover,e):this.store.hover&&this.store.hover.parentId?((t=this.store.active)==null?void 0:t.length)===1&&this.store.active[0].id===this.store.hover.id?this.showInput(this.store.hover):(this.store.pens[this.store.hover.parentId].children.forEach(i=>{this.store.pens[i].calculative.active=!1,this.store.pens[i].calculative.hover=!1}),this.active([this.store.hover])):this.showInput(this.store.hover)),this.store.emitter.emit("dblclick",{x:e.x,y:e.y,pen:this.store.hover})});ke(this,"showInput",(e,t,i="transparent")=>{if(!window||!this.store.hover||this.store.hover.locked||this.store.hover.externElement||this.store.hover.disableInput||this.store.hover.disabled)return;if(this.inputDiv.dataset.penId===e.id){this.inputDiv.dataset.isInput="true",this.inputDiv.contentEditable="true",this.inputDiv.focus();const u=window.getSelection();u.selectAllChildren(this.inputDiv),u.collapseToEnd(),this.inputDiv.scrollTop=this.inputDiv.scrollHeight,this.inputDiv.scrollLeft=this.inputDiv.scrollWidth;return}!t&&!e.dbInput?this.setInputStyle(e):(this.inputDiv.style.width="100%",this.inputDiv.style.height="100%");const r=t||e.calculative.worldTextRect,o=`${(e.calculative.tempText===void 0?e.text+""||"":e.calculative.tempText).replace(/\x20/g," ").split(/[\s\n]/).join("
")}
`.replace("","").replace(/\\<\/div\>/g,"

");this.inputDiv.innerHTML=o,this.inputParent.style.left=r.x+this.store.data.x-(e.calculative.textLeft||0)+"px",this.inputParent.style.top=r.y+this.store.data.y-(e.calculative.textTop||0)+"px";let l=r.width;this.inputParent.style.width=(l<0?12:l)+"px",this.inputParent.style.height=r.height+(e.textTop||0)+"px",this.inputParent.style.zIndex="9999",this.inputParent.style.background=i,e.rotate%360?this.inputParent.style.transform=`rotate(${e.rotate}deg)`:this.inputParent.style.transform=null,this.inputParent.style.display="flex",this.inputDiv.dataset.penId=e.id,this.inputDiv.contentEditable=e.disableInput==null?"true":e.disableInput.toString(),e.dropdownList&&this.dropdown.style.display!=="block"&&(this.dropdown.style.background=e.dropdownBackground||"#fff",this.dropdown.style.color=e.dropdownColor||"#bdc7db",this.dropdown.style.width=this.inputParent.style.width,this.dropdown.style.fontSize=(e.fontSize||12)+"px",this.setDropdownList(),this.externalElements.style.zIndex="9999"),this.inputDiv.contentEditable="true",this.inputDiv.focus();const c=window.getSelection();c.selectAllChildren(this.inputDiv),c.collapseToEnd(),this.inputDiv.scrollTop=this.inputDiv.scrollHeight,this.inputDiv.scrollLeft=this.inputDiv.scrollWidth,e.calculative.text=void 0,this.initTemplateCanvas([e]),this.render()});ke(this,"setInputStyle",e=>{e.text||(e.text="");let t;for(let l=0;l1?e.textLeft*n:e.textLeft*n/a}px;`),e.textTop&&(i+=`margin-top:${a>1?e.textTop*n:e.textTop*n/a}px;`),e.lineHeight&&(i+=`line-height:${a>1?e.fontSize*e.lineHeight*a:e.fontSize*e.lineHeight*n}px;`),e.textHeight)i+=`height:${a>1?e.textHeight*n*a:e.textHeight*n}px;`;else{let l=e.calculative.worldRect.height/a;l<0&&(l=0);let c=e.fontSize*a<12?l*n:l*a*n;c-1?e.textWidth*e.calculative.worldRect.width:e.textWidth,e.whiteSpace!=="pre-line"&&(o1?o*n*a:o*n}px;`);else if(e.whiteSpace===void 0||e.whiteSpace==="break-all"){let l=(e.calculative.worldTextRect.width||12)/a;l<0&&(l=0),i+=`width:${e.fontSize*a<12?l*n:l*a}px;`}if(e.whiteSpace&&(e.whiteSpace==="pre-line"?i+="white-space:pre;":(i+=`white-space:${e.whiteSpace};`,e.whiteSpace==="nowrap"&&(r+="display:contents;"))),e.whiteSpace!=="nowrap"){let l=e.fontSize*1.2*e.text.length,c=(o||e.calculative.worldRect.width/a)*Math.floor(e.calculative.worldRect.height/a/(e.lineHeight*e.fontSize));l>c&&(i+="justify-content: start;")}t.deleteRule(0),t.deleteRule(0),t.insertRule(`.meta2d-input .input-div{ resize:none;border:none;outline:none;background:transparent;position:absolute;flex-grow:1;height:100%;width: 100%;position:absolute;left:0;top:0;display:flex;flex-direction: column;cursor: text;${i}}`),t.insertRule(`.input-div div{${r}}`)});ke(this,"hideInput",()=>{if(this.externalElements.style.zIndex="5",this.inputParent.style.display==="flex"){this.inputParent.style.display="none";const e=this.store.pens[this.inputDiv.dataset.penId];if(!e)return;if(e.calculative.text=e.text,this.inputDiv.dataset.value=this.inputDiv.innerHTML.replace(/\/g,` `).replace(/\<\/div\>/g,"").replace(/\/g,"").replace(/ /g," ").replace(/(<([^>]+)>)/gi,""),this.inputDiv.dataset.value=this.convertSpecialCharacter(this.inputDiv.dataset.value),e.onInput)e.onInput(e,this.inputDiv.dataset.value);else if(e.text!==this.inputDiv.dataset.value){const t=[bt(e,!0)];e.text=this.inputDiv.dataset.value,e.calculative.text=e.text,this.inputDiv.dataset.penId=void 0,e.text&&e.textAutoAdjust&&!e.parentId&&yft(e),L1(e),this.patchFlags=!0,this.pushHistory({type:ur.Update,pens:[bt(e,!0)],initPens:t}),this.store.emitter.emit("change",e),this.store.emitter.emit("valueUpdate",e)}else e.text===this.inputDiv.dataset.value&&e.calculative.textLines.length==0&&L1(e);this.initTemplateCanvas([e])}this.inputDiv.dataset.penId=void 0,this.dropdown.style.display="none",this.inputDiv.dataset.isInput="false",this.inputDiv.contentEditable="false",this.render()});ke(this,"setDropdownList",e=>{this.clearDropdownList();const t=this.store.pens[this.inputDiv.dataset.penId];if(!this.store.data.locked&&!["tablePlus"].includes(t.name))return;if(this.dropdown.style.display="block",!t||!t.dropdownList){this.dropdown.style.display="none";return}if(!t.dropdownList.length){const n=document.createElement("div");n.innerText="None",n.style.padding="5px 12px",n.style.color="#ddd",this.dropdown.appendChild(n);return}const i=this.inputDiv.innerHTML.replace(/\/g,` `).replace(/\<\/div\>/g,"").replace(/\/g,"");let r=0;for(const n of t.dropdownList){const a=typeof n=="string"?n:n.text;e&&i?a.includes(i)&&this.dropdownAppendOption(a,r):this.dropdownAppendOption(a,r),++r}if(!this.dropdown.hasChildNodes()){const n=document.createElement("div");n.innerText="None",n.style.padding="5px 12px",n.style.color="#ddd",this.dropdown.appendChild(n)}});ke(this,"selectDropdown",e=>{const t=e.target,i=this.store.pens[this.inputDiv.dataset.penId];if(!t||!i||!i.dropdownList)return;const r=+t.dataset.i,n=i.dropdownList[r];if(!n)return;const a=[bt(i,!0)];typeof n=="object"?(this.updateValue(i,{...n}),i.calculative.text=void 0,this.calcActiveRect()):i.text=n+"",this.inputDiv.innerText=i.text,this.hideInput(),this.pushHistory({type:ur.Update,pens:[bt(i,!0)],initPens:a}),this.render(),this.store.emitter.emit("change",i),this.store.emitter.emit("valueUpdate",i)});ke(this,"inFitBorder",e=>{let t;const i=this.store.data.width||this.store.options.width,r=this.store.data.height||this.store.options.height;let n={x:(e.x-this.store.data.origin.x)/this.store.data.scale,y:(e.y-this.store.data.origin.y)/this.store.data.scale};const a=this.canvasImage.activeFit;this.externalElements.style.cursor="default",n.y>r*a.y-10&&n.yr*(a.y+a.height)-10&&n.yi*a.x-10&&n.xi*(a.x+a.width)-10&&n.x{this.patchFlags=!0,this.store.lastHover&&(this.store.lastHover.calculative.hover=!1);let n=this.store.data.pens.find(a=>a.calculative.hover===!0);pB(n,!1)},this.popconfirm=new A0t(t,i),this.dialog=new v0t(t,i),this.title=new J$(t),this.store.options.scroll&&(this.scroll=new iFe(this)),this.store.dpiRatio=globalThis.devicePixelRatio||1,this.store.dpiRatio<1?this.store.dpiRatio=1:this.store.dpiRatio>1&&this.store.dpiRatio<1.5&&(this.store.dpiRatio=1.5),this.clientRect=this.externalElements.getBoundingClientRect(),this.listen(),window==null||window.addEventListener("resize",this.onResize),window==null||window.addEventListener("scroll",this.onScroll),window==null||window.addEventListener("message",this.onMessage)}listen(){switch(this.externalElements.addEventListener("gesturestart",this.onGesturestart),this.externalElements.ondragover=e=>e.preventDefault(),this.externalElements.ondrop=this.ondrop,this.externalElements.oncontextmenu=e=>e.preventDefault(),this.store.options.interval=50,this.externalElements.ontouchstart=this.ontouchstart,this.externalElements.ontouchmove=this.ontouchmove,this.externalElements.ontouchend=this.ontouchend,this.externalElements.onmousedown=e=>{this.onMouseDown({x:e.offsetX,y:e.offsetY,clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,ctrlKey:e.ctrlKey||e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,buttons:e.buttons})},this.externalElements.onmousemove=e=>{e.target===this.externalElements&&this.onMouseMove({x:e.offsetX,y:e.offsetY,clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,ctrlKey:e.ctrlKey||e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,buttons:e.buttons})},this.externalElements.onmouseup=e=>{this.onMouseUp({x:e.offsetX,y:e.offsetY,clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,ctrlKey:e.ctrlKey||e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,buttons:e.buttons,button:e.button})},this.externalElements.onmouseleave=e=>{this.store.data.pens.forEach(t=>{t.calculative.hover&&(t.calculative.hover=!1)}),this.store.hover&&(this.store.hover.calculative.hover=!1,this.store.hover=void 0),this.render(),e.toElement!==this.tooltip.box&&e.toElement!==this.tooltip.arrowUp&&e.toElement!==this.tooltip.arrowDown&&(this.tooltip.hide(),this.store.lastHover=void 0)},this.externalElements.ondblclick=this.ondblclick,this.externalElements.tabIndex=0,this.externalElements.onblur=()=>{this.mouseDown=void 0},this.externalElements.onwheel=this.onwheel,document.addEventListener("copy",this.onCopy),document.addEventListener("cut",this.onCut),document.addEventListener("paste",this.onPaste),this.store.options.keydown){case fB.Document:document.addEventListener("keydown",this.onkeydown),document.addEventListener("keyup",this.onkeyup);break;case fB.Canvas:this.externalElements.addEventListener("keydown",this.onkeydown),this.externalElements.addEventListener("keyup",this.onkeyup);break}}splitLine(e,t){const i=e.calculative.worldAnchors,r=i.findIndex(u=>u===t);if([-1,0,i.length-1].includes(r))return;const n=bt(e,!0),a=bt(e,!0),o=fs();a.id=o,a.calculative.canvas=this,a.calculative.active=!1,a.calculative.hover=!1;const l=bt(i.slice(0,r+1)),c=bt(i.slice(r)).map(u=>(u.penId=o,u));e.calculative.worldAnchors=l,a.calculative.worldAnchors=c,this.initLineRect(e),this.initLineRect(a),this.store.data.pens.push(a),this.store.pens[o]=a,this.pushHistory({type:ur.Add,pens:[bt(a,!0)],step:2}),this.pushHistory({type:ur.Update,initPens:[n],pens:[bt(e,!0)],step:2})}translateAnchor(e,t){this.movingAnchor.x+=e,this.movingAnchor.y+=t;const i=this.movingAnchor.penId;if(i){const r=this.store.pens[i],n=r.calculative.worldRect;this.movingAnchor.xn.ex&&(this.movingAnchor.x=n.ex),this.movingAnchor.yn.ey&&(this.movingAnchor.y=n.ey);const a=kB(this.movingAnchor,n),o=r.anchors.findIndex(l=>l.id===this.movingAnchor.id);r.anchors[o]=a,this.patchFlags=!0}}async fileToPen(e,t){let i="";return this.store.options.uploadFn?i=await this.store.options.uploadFn(e):this.store.options.uploadUrl?i=await Aft(e,this.store.options.uploadUrl,this.store.options.uploadParams,this.store.options.uploadHeaders):i=await xft(e),new Promise((r,n)=>{const a=new Image;a.onload=()=>{Lr.htmlElements[i]=a,r({width:a.width,height:a.height,name:t?"gif":"image",image:i})},a.onerror=o=>{n(o)},a.crossOrigin="anonymous",a.src=i})}async dropPens(e,t){var l;this.randomIdObj={};for(const c of e)!c.parentId&&this.randomCombineId(c,e);if(Object.keys(this.randomIdObj).length!==0)for(const c of e)c.type?(c.anchors[0].connectTo=this.randomIdObj[c.anchors[0].connectTo],c.anchors[c.anchors.length-1].connectTo=this.randomIdObj[c.anchors[c.anchors.length-1].connectTo]):(l=c.connectedLines)==null||l.forEach(u=>{u.lineAnchor=this.randomIdObj[u.lineAnchor],u.lineId=this.randomIdObj[u.lineId]});for(const c of e)c.id||(c.id=fs()),!c.calculative&&(c.calculative={canvas:this}),this.store.pens[c.id]=c;let i=0,r=0,n=0;for(const c of e)c.parentId||(c.width*=this.store.data.scale,c.height*=this.store.data.scale,c.x=t.x-c.width/2+n,c.y=t.y-c.height/2+r,c.tags&&c.tags.includes("meta3d")&&(c.x=this.store.data.origin.x,c.y=this.store.data.origin.y),c.dataset&&(i%2===0?n=c.width-40*this.store.data.scale:n=0,i++,i%2===0&&(r+=c.height+10*this.store.data.scale)));const a=this.store.data.width||this.store.options.width,o=this.store.data.height||this.store.options.height;if(a&&o){let c={x:this.store.data.origin.x,y:this.store.data.origin.y,width:a*this.store.data.scale,height:o*this.store.data.scale},u=!0;for(const h of e)if(!h.parentId){let d=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x,y:h.y+h.height},{x:h.x+h.width,y:h.y+h.height},{x:h.x+h.width/2,y:h.y+h.height/2}];if(h.x===c.x&&h.y===c.y&&h.width===c.width&&h.height===c.height||d.some(f=>vy(f,c))){u=!1,this.store.options.strictScope&&(h.xc.x+c.width&&(h.x=c.x+c.width-h.width),h.y+h.height>c.y+c.height&&(h.y=c.y+c.height-h.height));break}}if(u){console.info("画笔在大屏范围外");return}}await this.addPens(e,!0),this.active(e.filter(c=>!c.parentId)),this.render(),this.externalElements.focus()}randomCombineId(e,t,i){let r=null;e.type?(e.anchors[0].connectTo||e.anchors[e.anchors.length-1].connectTo)&&(r=[e.id,e.anchors[0].id,e.anchors[e.anchors.length-1].id]):e.connectedLines&&e.connectedLines.length&&(r=[e.id]),oEe(e),r&&(r.length===1?this.randomIdObj[r[0]]=e.id:(this.randomIdObj[r[0]]=e.id,this.randomIdObj[r[1]]=e.anchors[0].id,this.randomIdObj[r[2]]=e.anchors[e.anchors.length-1].id)),e.parentId=i;const n=[];if(Array.isArray(e.children))for(const a of e.children){const o=t.find(l=>l.id===a);o&&n.push(this.randomCombineId(o,t,e.id).id)}return e.children=n,e}async addPens(e,t,i){if(this.beforeAddPens&&await this.beforeAddPens(e)!=!0)return[];const r=[];for(const n of e)this.beforeAddPen&&this.beforeAddPen(n)!=!0||(i&&(n.x=n.x*this.store.data.scale+this.store.data.origin.x,n.y=n.y*this.store.data.scale+this.store.data.origin.y,n.width=n.width*this.store.data.scale,n.height=n.height*this.store.data.scale),this.makePen(n),r.push(n));return this.render(),this.store.emitter.emit("add",r),t&&this.pushHistory({type:ur.Add,pens:bt(r,!0)}),r}getInitPencilLine(e){const{data:t,options:i}=this.store,r=t.scale,n=t.lineWidth||1;return{id:e.penId,name:"line",x:e.x,y:e.y,type:Kn.Line,calculative:{canvas:this,pencil:!0,active:!0,worldAnchors:[e],lineWidth:n*r},fromArrow:t.fromArrow||i.fromArrow,toArrow:t.toArrow||i.toArrow,lineWidth:n}}createDrawingLine(e){this.inactive();const{data:t,options:i}=this.store,r=t.scale,n=t.lineWidth||1;return e.penId=fs(),{id:e.penId,name:"line",lineName:this.drawingLineName,x:e.x,y:e.y,type:Kn.Line,calculative:{canvas:this,active:!0,worldAnchors:[e],lineWidth:n*r},fromArrow:t.fromArrow||i.fromArrow,toArrow:t.toArrow||i.toArrow,lineWidth:n}}addRuleLine(e){const{x:t,y:i,scale:r,origin:n}=this.store.data,a=e.x+t,o=e.y+i;let l=e.x,c=e.y,u=0,h=0,d=0,f=0;if(a<=o&&a<20)l=-t,u=this.width,d=1,e.ctrlKey||(c=Math.round((c-n.y)/(r*10))*(r*10)+n.y);else if(oe.isRuleLine)}alignPenToGrid(e){var i;if(this.store.options.autoAlignGrid&&this.store.data.grid&&!e.type){const r=this.store.data.gridSize||this.store.options.gridSize,{origin:n,scale:a}=this.store.data,{x:o,y:l}=e,c={x:o,y:l},u=this.getPenRect(e),h=parseInt((u.x/r).toFixed()),d=parseInt((u.y/r).toFixed()),f=h*r,p=d*r;c.x=n.x+f*a,c.y=n.y+p*a,Object.assign(e,c),(i=e.onMove)==null||i.call(e,e),this.updatePenRect(e),this.calcActiveRect(),this.getSizeCPs()}}movedActivePens(e){let t=this.getAllFollowersByPens(this.store.active,!1);const i=bt(t,!0),r=this.store.data.gridSize||this.store.options.gridSize,{origin:n,scale:a}=this.store.data,o=this.store.options.autoAlignGrid&&this.store.data.grid;if(t.forEach(d=>{var _;const f=this.movingPens.findIndex(y=>y.id===d.id+Td);if(f<0)return;const{x:p,y:m}=this.movingPens[f],g={x:p,y:m};if(o&&!this.movingPens[f].type){const y=this.getPenRect(this.movingPens[f]),v=parseInt((y.x/r).toFixed()),x=parseInt((y.y/r).toFixed()),A=v*r,b=x*r;g.x=n.x+A*a,g.y=n.y+b*a}Object.assign(d,g),(_=d.onMove)==null||_.call(d,d),this.updatePenRect(d),this.updateLines(d),this.store.emitter.emit("updateLines",d),this.patchFlagsLines.forEach(y=>{y.type&&this.initLineRect(y)}),this.patchFlagsLines.clear(),d.calculative.x=d.x,d.calculative.y=d.y,d.calculative.initRect&&(d.calculative.initRect.x=d.calculative.x,d.calculative.initRect.y=d.calculative.y,d.calculative.initRect.ex=d.calculative.x+d.calculative.width,d.calculative.initRect.ey=d.calculative.y+d.calculative.height),VNe(d),d.parentId&&this.parent.updateRectbyChild(d.calculative.worldRect,d,this.store.pens[d.parentId])}),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),!this.dock)return;const{xDock:l,yDock:c}=this.dock;let u;l&&(u=this.store.pens[l.penId]),!u&&c&&(u=this.store.pens[c.penId]);const h=bt(this.store.active,!0);if(e&&this.store.active.length===1&&(u==null?void 0:u.type)===1&&(l!=null&&l.anchorId||c!=null&&c.anchorId)){const d=rl(u),f=Dn(u);if(l!=null&&l.anchorId){const p=this.store.pens[this.store.active[0].id+Td].calculative.worldAnchors.find(m=>m.id===l.anchorId);p.x===d.x&&p.y===d.y?(i.push(bt(u,!0)),Zc(this.store.active[0],p,u,d),h.push(bt(u,!0))):p.x===f.x&&p.y===f.y&&(i.push(bt(u,!0)),Zc(this.store.active[0],p,u,f),h.push(bt(u,!0)))}else if(c!=null&&c.anchorId){const p=this.store.pens[this.store.active[0].id+Td].calculative.worldAnchors.find(m=>m.id===c.anchorId);p.x===d.x&&p.y===d.y?(i.push(bt(u,!0)),Zc(this.store.active[0],p,u,d),h.push(bt(u,!0))):p.x===f.x&&p.y===f.y&&(i.push(bt(u,!0)),Zc(this.store.active[0],p,u,f),h.push(bt(u,!0)))}}o&&(this.calcActiveRect(),this.getSizeCPs()),this.pushHistory({type:ur.Update,pens:h,initPens:i}),this.store.emitter.emit("translatePens",h)}copyMovedPens(){this.copy(this.store.active.map((e,t)=>{const{x:i,y:r}=this.movingPens[t];return this.updateLines(e),{...e,x:i,y:r}})),this.pasteOffset=!1,this.paste()}initImageCanvas(e){e.some(t=>this.hasImage(t,!1))&&this.canvasImage.init(),e.some(t=>this.hasImage(t,!0))&&this.canvasImageBottom.init()}initTemplateCanvas(e){e.some(t=>t.canvasLayer===hn.CanvasTemplate)&&this.canvasTemplate.init()}hasImage(e,t){var i;return e.image&&e.name!=="gif"?t?e.canvasLayer===hn.CanvasImageBottom:e.canvasLayer===hn.CanvasImage:(i=e.children)==null?void 0:i.some(r=>{const n=this.store.pens[r];return n&&this.hasImage(n,t)})}inactive(e){this.store.active.length&&(this.initTemplateCanvas(this.store.active),this.store.active.forEach(t=>{t.calculative.active=void 0,t.calculative.activeAnchor=void 0,t.calculative.hover=!1,v5(t,!1)}),!e&&this.store.emitter.emit("inactive",this.store.active),this.store.active=[],this.activeRect=void 0,this.sizeCPs=void 0,this.store.activeAnchor=void 0,this.patchFlags=!0)}active(e,t=!0){if(this.store.active){t&&this.store.emitter.emit("inactive",this.store.active);for(const i of this.store.active)i.calculative.active=void 0,i.calculative.hover=!1,v5(i,!1)}this.store.active=[],e.forEach(i=>{i.calculative.active=!0,v5(i)}),this.store.active.push(...e),this.activeRect=void 0,this.calcActiveRect(),this.initTemplateCanvas(e),this.patchFlags=!0,t&&this.store.emitter.emit("active",this.store.active)}getSizeCPs(){this.sizeCPs=yv(this.activeRect);const e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}],{x:t,y:i,width:r,height:n,rotate:a,center:o}=this.activeRect;e.forEach(l=>{const c={x:l.x*r+t,y:l.y*n+i};Pa(c,a,o),this.sizeCPs.push(c)})}getSpecialAngle(e,t){let i=0;e.x-t.x!==0?(i=Math.atan((t.y-e.y)/(e.x-t.x))*180/Math.PI,e.x0?i-=180:i+=180)):t.y>e.y?i=90:t.yqs.DisableEdit||!(t.type&&t.calculative.active)&&this.store.options.disableAnchor||t.disableAnchor)return pr.None;if((this.mouseDown||this.drawingLine)&&t.name==="line"&&i.connectTo){const n=this.findOne(i.connectTo);if(n!=null&&n.calculative&&!(n!=null&&n.calculative.active)){t=n;const a=n.calculative.worldAnchors.find(o=>o.id===i.anchorId);a&&(i=a)}}if(i.twoWay===uh.Disable&&t.name!=="line")return pr.None;if(t.name==="line"&&i.connectTo){let n=(r=this.findOne(i.connectTo))==null?void 0:r.anchors.find(a=>a.id===i.anchorId);if(n&&n.twoWay)return pr.None}if(this.drawingLine){if(i.twoWay===uh.Out)return pr.None}else if(!(this.mouseDown&&this.hoverType===pr.LineAnchor)){if(i.twoWay===uh.In)return pr.None}if(g5(e,i,this.pointSize,i.penId?this.store.pens[i.penId]:void 0))return i!==this.store.hoverAnchor&&(this.patchFlags=!0),this.store.hoverAnchor=i,this.store.hover=t,t.type?i.connectTo&&!t.calculative.active&&(this.store.hover=this.store.pens[i.connectTo],this.store.hover)?(this.store.hoverAnchor=this.store.hover.calculative.worldAnchors.find(n=>n.id===i.anchorId),this.store.hoverAnchor?(this.externalElements.style.cursor="crosshair",pr.NodeAnchor):pr.None):(this.hotkeyType===ia.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="pointer",pr.LineAnchor):(this.hotkeyType===ia.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="crosshair",pr.NodeAnchor);if(!this.mouseDown&&t.type){if(t.calculative.active&&i.prev&&g5(e,i.prev,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=t,this.externalElements.style.cursor="pointer",pr.LineAnchorPrev;if(t.calculative.active&&i.next&&g5(e,i.next,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=t,this.externalElements.style.cursor="pointer",pr.LineAnchorNext}return pr.None}resize(e,t){e=e||this.parentElement.clientWidth,t=t||this.parentElement.clientHeight,this.width=e,this.height=t,this.canvasRect={x:0,y:0,width:e,height:t},Go(this.canvasRect),this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",this.externalElements.style.width=e+"px",this.externalElements.style.height=t+"px",this.canvasTemplate.resize(e,t),this.canvasImage.resize(e,t),this.canvasImageBottom.resize(e,t),this.magnifierCanvas.resize(e,t),e=e*this.store.dpiRatio|0,t=t*this.store.dpiRatio|0,this.canvas.width=e,this.canvas.height=t,this.offscreen.width=e,this.offscreen.height=t,this.clientRect=this.externalElements.getBoundingClientRect(),this.canvas.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle";for(const i of this.store.data.pens)i.isRuleLine&&(i.width?i.height||(i.width=this.width):i.height=this.height),sv(i);this.render()}clearCanvas(){this.activeRect=void 0,this.sizeCPs=void 0,this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.offscreen.getContext("2d").clearRect(0,0,this.offscreen.width,this.offscreen.height),this.store.data.template||this.canvasTemplate.clear(),this.canvasImage.clear(),this.canvasImageBottom.clear()}async addPen(e,t,i,r){if(!(this.beforeAddPens&&await this.beforeAddPens([e])!=!0)&&!(this.beforeAddPen&&this.beforeAddPen(e)!=!0))return r&&(e.x=e.x*this.store.data.scale+this.store.data.origin.x,e.y=e.y*this.store.data.scale+this.store.data.origin.y,e.width=e.width*this.store.data.scale,e.height=e.height*this.store.data.scale),this.makePen(e),this.active([e]),this.render(),i&&this.store.emitter.emit("add",[e]),t&&this.pushHistory({type:ur.Add,pens:[e]}),e}pushHistory(e){var r;if(this.store.data.locked)return;const{origin:t,scale:i}=this.store.data;e.origin=bt(t),e.scale=i,e.type!==ur.Update&&e.pens&&e.pens.forEach(n=>{n.calculative&&(n.calculative.layer=this.store.data.pens.findIndex(a=>a.id===n.id))}),this.store.historyIndex{let a;if(e.initPens)for(const o of e.initPens)o.id===n.id&&(a=o);if(a)for(const o in n)a[o]==null&&(a[o]=void 0)}),this.store.histories.push(e),this.store.historyIndex=this.store.histories.length-1,this.store.emitter.emit("update",{previous:e.initPens,current:e.pens})}undo(){if(this.store.data.locked||this.store.historyIndex==null||this.store.historyIndex<0)return;const e=this.store.histories[this.store.historyIndex--];this.doEditAction(e,!0);let t=e.step;for(;t>1;){const i=this.store.histories[this.store.historyIndex--];this.doEditAction(i,!0),t--}(e.type==ur.Add||e.type==ur.Delete||e.type==ur.Update)&&this.activeHistory()}redo(){if(this.store.data.locked||this.store.historyIndex==null||this.store.historyIndex>this.store.histories.length-2)return;const e=this.store.histories[++this.store.historyIndex];this.doEditAction(e,!1);let t=e.step;for(;t>1;){const i=this.store.histories[++this.store.historyIndex];this.doEditAction(i,!1),t--}(e.type==ur.Add||e.type==ur.Delete||e.type==ur.Update)&&this.activeHistory()}activeHistory(){let e=this.store.histories[this.store.historyIndex+1];const t=[];if(e&&e.type===ur.Update){e.pens.forEach(r=>{t.push(this.store.pens[r.id])}),this.active(t);return}let i=this.store.histories[this.store.historyIndex];i&&(i.type===ur.Add||i.type===ur.Delete)&&(i.pens.forEach(r=>{t.push(this.store.pens[r.id])}),this.active(t))}doEditAction(e,t){switch(this.inactive(),this.store.hoverAnchor=void 0,this.store.hover=void 0,e.type){case ur.Add:e.pens.forEach(n=>{var l;const a=bt(n,!0),o=this.store.data.pens.findIndex(c=>c.id===a.id);o>-1&&((l=a.onDestroy)==null||l.call(a,this.store.pens[a.id]),this.store.data.pens.splice(o,1),this.store.pens[a.id]=void 0,a.calculative||(a.calculative={}),a.calculative.canvas=this,this.store.animates.delete(a),this.store.animateMap.delete(a))}),e.type=ur.Delete;break;case ur.Update:const i=t?e.initPens:e.pens,r=t?e.pens:e.initPens;i.forEach(n=>{const a=bt(n,!0),o=this.store.data.pens.findIndex(l=>l.id===a.id);if(o>-1){if(a.calculative=this.store.data.pens[o].calculative,this.store.data.pens[o].type&&this.store.data.pens[o].lastConnected){for(let c in this.store.data.pens[o].lastConnected)if(this.store.pens[c]){let u=bt(this.store.data.pens[o].lastConnected[c]);this.store.pens[c].connectedLines=u,a.anchors.forEach(h=>{u.forEach(d=>{h.id===d.lineAnchor&&(h.connectTo=c)})})}}this.store.data.pens[o]=a,this.store.pens[a.id]=a;for(const c in a)(typeof a[c]!="object"||c==="lineDash")&&(a.calculative[c]=a[c]);a.calculative.image=void 0;const l=this.getPenRect(a,e.origin,e.scale);if(this.setPenRect(a,l,!1),this.updateLines(a,!0),a.calculative.canvas.parent.isCombine(a)){let c=r.find(u=>u.id===a.id);ANe.forEach(u=>{a[u]!==c[u]&&this.parent.setValue({id:a.id,[u]:a[u]},{render:!0,doEvent:!1})})}}});break;case ur.Delete:e.pens.reverse().forEach(n=>{var o,l;const a=bt(n,!0);if(a.calculative||(a.calculative={}),this.store.data.pens.splice(((o=a.calculative)==null?void 0:o.layer)!==-1?(l=a.calculative)==null?void 0:l.layer:this.store.data.pens.length,0,a),this.store.pens[a.id]=a,a.type&&a.lastConnected)for(let c in a.lastConnected)this.store.pens[c]&&(this.store.pens[c].connectedLines=a.lastConnected[c]);a.calculative.canvas=this}),e.pens.reverse().forEach(n=>{const a=this.store.pens[n.id],o=this.getPenRect(a,e.origin,e.scale);this.setPenRect(a,o,!1),a.calculative.image=void 0,a.calculative.backgroundImage=void 0,a.calculative.strokeImage=void 0,this.loadImage(a)}),e.type=ur.Add;break;case ur.Replace:{const n=t?e.initPens:e.pens;(t?e.pens:e.initPens).forEach(o=>{var u;const l=bt(o,!0);if(this.store.data.pens.findIndex(h=>h.id===l.id)>-1){(u=l.onDestroy)==null||u.call(l,this.store.data.pens.find(d=>d.id===l.id));const h=this.store.data.pens.findIndex(d=>d.id===l.id);this.store.data.pens.splice(h,1),this.store.pens[l.id]=void 0,l.calculative||(l.calculative={}),l.calculative.canvas=this,this.store.animates.delete(l),this.store.animateMap.delete(l)}}),n.reverse().forEach(o=>{var c,u;const l=bt(o,!0);if(l.calculative||(l.calculative={}),this.store.data.pens.splice(((c=l.calculative)==null?void 0:c.layer)!==-1?(u=l.calculative)==null?void 0:u.layer:this.store.data.pens.length,0,l),this.store.pens[l.id]=l,l.type&&l.lastConnected)for(let h in l.lastConnected)this.store.pens[h]&&(this.store.pens[h].connectedLines=l.lastConnected[h]);l.calculative.canvas=this}),n.reverse().forEach(o=>{const l=this.store.data.pens.find(u=>u.id===o.id),c=this.getPenRect(l,e.origin,e.scale);this.setPenRect(l,c,!1),l.calculative.image=void 0,l.calculative.backgroundImage=void 0,l.calculative.strokeImage=void 0,this.loadImage(l)}),e.type=ur.Replace;break}}if(e.type===ur.Update){let i=[...e.pens,...e.initPens];this.initImageCanvas(i),this.initTemplateCanvas(i)}else this.initImageCanvas(e.pens),this.initTemplateCanvas(e.pens);this.parent.onSizeUpdate(),this.render(),this.store.emitter.emit(t?"undo":"redo",e)}makePen(e){var r;if(e.id||(e.id=fs()),Math.abs(this.store.lastScale-this.store.data.scale)<1e-4&&this.store.sameTemplate&&this.store.templatePens[e.id]&&e.canvasLayer===hn.CanvasTemplate){e=this.store.templatePens[e.id],this.store.data.pens.push(e),this.updatePenRect(e);return}if(e.copyIndex?(this.store.data.pens.splice(e.copyIndex+1,0,e),delete e.copyIndex):this.store.data.pens.push(e),this.store.pens[e.id]=e,e.path){!e.pathId&&(e.pathId=fs());const n=this.store.data.paths;!n[e.pathId]&&(n[e.pathId]=e.path),e.path=void 0}e.lineWidth==null&&(e.lineWidth=1);const{fontSize:t,lineHeight:i}=this.store.options;e.fontSize?e.fontSize<0&&(e.fontSize=0):e.fontSize=t>=0?t:12,e.lineHeight||(e.lineHeight=i),e.image&&e.name!=="gif"&&e.canvasLayer===void 0&&(e.isBottom?e.canvasLayer=hn.CanvasImageBottom:e.canvasLayer=hn.CanvasImage,delete e.isBottom),e.template&&(e.canvasLayer=hn.CanvasTemplate),e.calculative={canvas:this,singleton:(r=e.calculative)==null?void 0:r.singleton},(e.video||e.audio)&&(e.calculative.onended=n=>{this.nextAnimate(n)});for(const n in e)(typeof e[n]!="object"||n==="lineDash")&&(e.calculative[n]=e[n]);if(e.calculative.image=void 0,e.calculative.backgroundImage=void 0,e.calculative.strokeImage=void 0,!e.anchors&&Lr.anchors[e.name]&&(e.anchors||(e.anchors=[]),Lr.anchors[e.name](e)),!e.anchors){const n=bt(this.store.options.defaultAnchors);n.forEach((a,o)=>{a.id=`${o}`,a.penId=e.id}),e.anchors=n}this.updatePenRect(e),!e.anchors&&e.calculative.worldAnchors&&(e.anchors=e.calculative.worldAnchors.map(n=>kB(n,e.calculative.worldRect))),!e.rotate&&(e.rotate=0),this.loadImage(e),this.parent.penNetwork(e)}drawline(e){var t;this.drawingLine&&((t=this[this.drawingLineName])==null||t.call(this,this.store,this.drawingLine,e),this.store.path2dMap.set(this.drawingLine,Lr.path2dDraws.line(this.drawingLine)),this.patchFlags=!0)}initLineRect(e){var n;if(!e)return;if(!((n=e.calculative.worldAnchors)!=null&&n.length)){this._del([e]);return}if(!isFinite(e.x)||!isFinite(e.x)||e.x==null||e.y==null)return;const t=rue(e);e.parentId||Object.assign(e,t);const{fontSize:i,lineHeight:r}=this.store.options;e.fontSize||(e.fontSize=i>=0?i:12,e.calculative.fontSize=e.fontSize*this.store.data.scale),e.lineHeight||(e.lineHeight=r,e.calculative.lineHeight=e.lineHeight),ro(t),e.calculative.worldRect=t,zme(e,t),L1(e),sv(e),e.calculative&&(e.calculative.gradientAnimatePath=void 0),this.store.path2dMap.set(e,Lr.path2dDraws[e.name](e)),e.calculative.worldAnchors&&(e.anchors=e.calculative.worldAnchors.map(a=>kB(a,e.calculative.worldRect)))}drawingPencil(){rFe(this.store),this.pencil=!0,this.externalElements.style.cursor="crosshair"}stopPencil(){this.pencil=!1,this.pencilLine=void 0,this.externalElements.style.cursor="default"}async finishDrawline(e){if(!this.drawingLine)return;const t=rl(this.drawingLine);let i=Dn(this.drawingLine);if(i.isTemp&&(this.drawingLine.calculative.worldAnchors.pop(),i=Dn(this.drawingLine)),!e&&(!i.connectTo&&this.drawingLine.calculative.worldAnchors.pop(),rl(this.drawingLine)===this.drawingLine.calculative.activeAnchor)){this.drawingLine=void 0,this.render();return}if(!t.connectTo||!i.connectTo){if(this.store.options.disableEmptyLine){t.connectTo&&(this.store.pens[t.connectTo].connectedLines=this.store.pens[t.connectTo].connectedLines.filter(a=>a.lineId!==this.drawingLine.id)),this.drawingLine=void 0,this.render();return}}else if(this.store.options.disableRepeatLine&&this.store.data.pens.find(o=>{if(o.type){const l=rl(o),c=Dn(o);return $6e(l,t)&&$6e(c,i)}})){this.drawingLine=void 0,this.render();return}const r=rue(this.drawingLine);Object.assign(this.drawingLine,r),this.drawingLine.calculative.worldRect=r,this.drawingLine.calculative.activeAnchor=Dn(this.drawingLine),this.store.activeAnchor=this.drawingLine.calculative.activeAnchor,(!this.beforeAddPens||await this.beforeAddPens([this.drawingLine]))&&(!this.beforeAddPen||this.beforeAddPen(this.drawingLine))&&(this.initLineRect(this.drawingLine),this.store.data.pens.push(this.drawingLine),this.store.pens[this.drawingLine.id]=this.drawingLine,this.store.emitter.emit("add",[this.drawingLine]),this.active([this.drawingLine]),this.pushHistory({type:ur.Add,pens:bt([this.drawingLine],!0)})),this.store.path2dMap.set(this.drawingLine,Lr.path2dDraws[this.drawingLine.name](this.drawingLine)),this.drawingLine=void 0,this.drawingLineName=void 0,this.render()}async finishPencil(){if(this.pencilLine){const e=nue(this.pencilLine.calculative.worldAnchors,10,0,this.pencilLine.calculative.worldAnchors.length-1);let t=rl(this.pencilLine);e.unshift({id:t.id,penId:t.penId,x:t.x,y:t.y}),t=Dn(this.pencilLine),e.push({id:t.id,penId:t.penId,x:t.x,y:t.y}),this.pencilLine.calculative.worldAnchors=s0t(e),this.pencilLine.calculative.worldAnchors.length>1&&(this.pencilLine.calculative.pencil=!1,this.store.path2dMap.set(this.pencilLine,Lr.path2dDraws[this.pencilLine.name](this.pencilLine)),(!this.beforeAddPens||await this.beforeAddPens([this.pencilLine]))&&(!this.beforeAddPen||this.beforeAddPen(this.pencilLine))&&(this.initLineRect(this.pencilLine),this.store.data.pens.push(this.pencilLine),this.store.pens[this.pencilLine.id]=this.pencilLine,this.store.emitter.emit("add",[this.pencilLine]),this.active([this.pencilLine]),this.pushHistory({type:ur.Add,pens:bt([this.pencilLine],!0)}))),this.pencilLine=void 0,this.render()}}firefoxLoadSvg(e){const t=new Image,i=new XMLHttpRequest;i.open("GET",e.image,!0),i.onload=()=>{const a=new DOMParser().parseFromString(i.responseText,"text/xml").getElementsByTagName("svg")[0],{width:o,height:l}=e.calculative.worldRect;a.setAttribute("width",`${o}px`),a.setAttribute("height",`${l}px`);const u="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(new XMLSerializer().serializeToString(a))));t.src=u,t.onload=()=>{e.calculative.img=t,e.calculative.imgNaturalWidth=t.naturalWidth||e.iconWidth,e.calculative.imgNaturalHeight=t.naturalHeight||e.iconHeight,Lr.htmlElements[e.image]=t,this.imageLoaded(),e.canvasLayer===hn.CanvasTemplate&&this.templateImageLoaded()}},i.send()}loadImage(e){if(e.image!==e.calculative.image||!e.calculative.img){if(e.calculative.img=void 0,e.image)if(Lr.htmlElements[e.image]){const t=Lr.htmlElements[e.image];e.calculative.img=t,e.calculative.imgNaturalWidth=t.naturalWidth||e.iconWidth,e.calculative.imgNaturalHeight=t.naturalHeight||e.iconHeight,this.imageLoaded(),e.canvasLayer===hn.CanvasTemplate&&this.templateImageLoaded()}else if(navigator.userAgent.includes("Firefox")&&e.image.endsWith(".svg"))this.firefoxLoadSvg(e);else{const t=new Image;t.crossOrigin=e.crossOrigin==="undefined"?void 0:e.crossOrigin||"anonymous",t.src=e.image,this.store.options.cdn&&!(e.image.startsWith("http")||e.image.startsWith("//")||e.image.startsWith("data:image"))&&(t.src=this.store.options.cdn+e.image),t.onload=()=>{e.calculative.img=t,e.calculative.imgNaturalWidth=t.naturalWidth||e.iconWidth,e.calculative.imgNaturalHeight=t.naturalHeight||e.iconHeight,Lr.htmlElements[e.image]=t,this.imageLoaded(),e.canvasLayer===hn.CanvasTemplate&&this.templateImageLoaded()}}e.calculative.image=e.image}if(e.backgroundImage!==e.calculative.backgroundImage){if(e.calculative.backgroundImg=void 0,e.backgroundImage)if(Lr.htmlElements[e.backgroundImage]){const t=Lr.htmlElements[e.backgroundImage];e.calculative.backgroundImg=t}else{const t=new Image;t.crossOrigin="anonymous",t.src=e.backgroundImage,this.store.options.cdn&&!(e.backgroundImage.startsWith("http")||e.backgroundImage.startsWith("//")||e.backgroundImage.startsWith("data:image"))&&(t.src=this.store.options.cdn+e.backgroundImage),t.onload=()=>{e.calculative.backgroundImg=t,Lr.htmlElements[e.backgroundImage]=t,this.imageLoaded(),e.canvasLayer===hn.CanvasTemplate&&this.templateImageLoaded()}}e.calculative.backgroundImage=e.backgroundImage}if(e.strokeImage!==e.calculative.strokeImage){if(e.calculative.strokeImg=void 0,e.strokeImage)if(Lr.htmlElements[e.strokeImage]){const t=Lr.htmlElements[e.strokeImage];e.calculative.strokeImg=t}else{const t=new Image;t.crossOrigin="anonymous",t.src=e.strokeImage,this.store.options.cdn&&!(e.strokeImage.startsWith("http")||e.strokeImage.startsWith("//")||e.strokeImage.startsWith("data:image"))&&(t.src=this.store.options.cdn+e.strokeImage),t.onload=()=>{e.calculative.strokeImg=t,Lr.htmlElements[e.strokeImage]=t,this.imageLoaded(),e.canvasLayer===hn.CanvasTemplate&&e.name!=="gif"&&this.templateImageLoaded()}}e.calculative.strokeImage=e.strokeImage}}imageLoaded(){this.imageTimer&&clearTimeout(this.imageTimer),this.imageTimer=setTimeout(()=>{this.canvasImage.init(),this.canvasImageBottom.init(),this.render()},100)}templateImageLoaded(){this.templateImageTimer&&clearTimeout(this.templateImageTimer),this.templateImageTimer=setTimeout(()=>{this.canvasTemplate.init(),this.render()},100)}setCalculativeByScale(e){const t=this.store.data.scale;e.calculative.lineWidth=e.lineWidth*t,e.calculative.fontSize=e.fontSize*t,e.fontSize<1&&e.fontSize>0&&(e.calculative.fontSize=e.fontSize*e.calculative.worldRect.height),e.calculative.iconSize=e.iconSize*t,e.calculative.iconWidth=e.iconWidth*t,e.calculative.iconHeight=e.iconHeight*t,e.calculative.iconLeft=e.iconLeft<1&&e.iconLeft>-1?e.iconLeft:e.iconLeft*t,e.calculative.iconTop=e.iconTop<1&&e.iconTop>-1?e.iconTop:e.iconTop*t,e.calculative.textWidth=e.textWidth<1&&e.textWidth>-1?e.textWidth:e.textWidth*t,e.calculative.textHeight=e.textHeight<1&&e.textHeight>-1?e.textHeight:e.textHeight*t,e.calculative.textLeft=e.textLeft<1&&e.textLeft>-1?e.textLeft*e.calculative.worldRect.width:e.textLeft*t,e.calculative.textTop=e.textTop<1&&e.textTop>-1?e.textTop*e.calculative.worldRect.height:e.textTop*t,e.type===Kn.Line&&e.borderWidth&&(e.calculative.borderWidth=e.borderWidth*t)}updatePenRect(e,{worldRectIsReady:t,playingAnimate:i}={}){t?GQ(e):zNe(e),i||this.setCalculativeByScale(e),eP(e),J6e(this.store.pens,e),L1(e),sv(e),Lr.path2dDraws[e.name]&&this.store.path2dMap.set(e,Lr.path2dDraws[e.name](e)),e.calculative.patchFlags=!0,this.patchFlags=!0,e.children&&e.children.forEach(r=>{const n=this.store.pens[r];n&&this.updatePenRect(n,{worldRectIsReady:!1})}),e.type&&this.initLineRect(e),e.calculative.gradientTimer&&clearTimeout(e.calculative.gradientTimer),e.calculative.gradientTimer=setTimeout(()=>{e.calculative.lineGradient&&(e.calculative.lineGradient=null),e.calculative.gradient&&(e.calculative.gradient=null),e.calculative.radialGradient&&(e.calculative.radialGradient=null),this.patchFlags=!0,e.calculative.gradientTimer=void 0},50)}initGlobalStyle(){const e={},t={},i={};fft.forEach(r=>{var n;if(this.store.options[r]!==void 0&&(e[r]=this.store.options[r]),this.store.data[r]!==void 0&&(t[r]=this.store.data[r]),this.store.data.theme){const a=(n=this.store.theme[this.store.data.theme])==null?void 0:n[r];a!==void 0&&(i[r]=a)}}),this.store.styles={},Object.assign(this.store.styles,e,t,i)}translate(e=0,t=0){if(this.store.data.x+=e*this.store.data.scale,this.store.data.y+=t*this.store.data.scale,this.store.data.x=Math.round(this.store.data.x),this.store.data.y=Math.round(this.store.data.y),this.store.options.padding){let i=rv(this.store.options.padding);const r=this.store.data.width||this.store.options.width,n=this.store.data.height||this.store.options.height;this.width<(r+i[1]+i[3])*this.store.data.scale&&(this.store.data.x+this.store.data.origin.x>i[3]*this.store.data.scale&&(this.store.data.x=i[3]*this.store.data.scale-this.store.data.origin.x),this.store.data.x+this.store.data.origin.x+r*this.store.data.scalei[0]*this.store.data.scale&&(this.store.data.y=i[0]*this.store.data.scale-this.store.data.origin.y),this.store.data.y+this.store.data.origin.y+n*this.store.data.scale{this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init(),this.render()},300)):(this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init(),this.render()),this.store.emitter.emit("translate",{x:this.store.data.x,y:this.store.data.y}),this.tooltip.translate(e,t),this.scroll&&this.scroll.isShow&&this.scroll.translate(e,t),this.onMovePens()}onMovePens(){var t;const e=this.parent.map;e&&e.isShow&&e.setView();for(const i of this.store.data.pens)sv(i),(t=i.onMove)==null||t.call(i,i),i.isRuleLine&&(i.width?i.height||(i.x=-this.store.data.x):i.y=-this.store.data.y,this.updatePenRect(i))}scale(e,t={x:0,y:0}){var o;const i=this.store.data.minScale||this.store.options.minScale,r=this.store.data.maxScale||this.store.options.maxScale;if(!(e>=i&&e<=r))return;this.calibrateMouse(t);const n=e/this.store.data.scale;this.store.data.scale=e,this.store.data.center=t,(o=this.store.clipboard)!=null&&o.pos&&j$(this.store.clipboard.pos,n,t),j$(this.store.data.origin,n,t),this.store.data.pens.forEach(l=>{if(!l.parentId){if(wI(l,n,t),l.onScale&&l.onScale(l),l.isRuleLine){const c=1/n,u=l.calculative.worldRect.center;l.width&&l.height||wI(l,c,u)}this.updatePenRect(l,{worldRectIsReady:!0}),this.execPenResize(l)}}),this.onMovePens(),this.calcActiveRect(),this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init();const a=this.parent.map;a&&a.isShow&&a.setView(),this.render(),this.store.emitter.emit("scale",this.store.data.scale)}templateScale(e,t={x:0,y:0}){const{minScale:i,maxScale:r}=this.store.options;if(!(e>=i&&e<=r))return;const n=e/this.store.data.scale;this.store.data.scale=e,this.store.data.center={x:0,y:0},this.store.data.origin={x:0,y:0},this.store.data.pens.forEach(a=>{if(!a.parentId){if(wI(a,n,t),a.onScale&&a.onScale(a),a.isRuleLine){const o=n>1?1:1/n/n,l=a.calculative.worldRect.center;a.width&&a.height||wI(a,o,l)}this.execPenResize(a)}}),this.calcActiveRect()}rotatePens(e){this.initPens||(this.initPens=bt(this.getAllByPens(this.store.active))),this.activeRect.rotate=a0(e,this.activeRect.center),this.activeRect.rotate%90<10&&(this.activeRect.rotate-=this.activeRect.rotate%90),this.activeRect.rotate%90>80&&(this.activeRect.rotate+=90-this.activeRect.rotate%90),this.store.active.length===1&&(this.lastRotate=this.store.active[0].rotate||0);const t=this.activeRect.rotate-this.lastRotate;for(const i of this.store.active){if(i.parentId)return;this.rotatePen(i,t,this.activeRect),i.onRotate&&i.onRotate(i),this.updateLines(i)}this.lastRotate=this.activeRect.rotate,this.getSizeCPs(),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),this.render(),this.store.emitter.emit("rotatePens",this.store.active),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:ur.Update,pens:bt(this.getAllByPens(this.store.active)),initPens:this.initPens}),this.initPens=void 0},200)}resizePens(e){if(this.initPens||(this.initPens=bt(this.store.active,!0)),!this.initActiveRect){this.initActiveRect=bt(this.activeRect);return}const t={x:this.mouseDown.x,y:this.mouseDown.y},i={x:e.x,y:e.y};let r=i.x-t.x,n=i.y-t.y;const a=bt(this.initActiveRect);if(lEe(a,r,n,this.resizeIndex),ro(a),!this.store.options.disableDock){this.clearDock();const f=this.customResizeDock||apt;this.dock=f(this.store,a,this.store.active,this.resizeIndex);const{xDock:p,yDock:m}=this.dock;if(p){r+=p.step;const g=this.store.pens[p.penId];g.calculative.isDock=!0}if(m){n+=m.step;const g=this.store.pens[m.penId];g.calculative.isDock=!0}}const o=this.activeRect.width,l=this.activeRect.height;let c=r-this.lastOffsetX,u=n-this.lastOffsetY;if(this.lastOffsetX=r,this.lastOffsetY=n,(e.ctrlKey||this.initPens.length===1&&this.initPens[0].ratio)&&(u=([1,3].includes(this.resizeIndex)?-1:1)*(c*l)/o),this.activeRect.ratio=this.initPens[0].ratio,lEe(this.activeRect,c,u,this.resizeIndex),this.store.options.strictScope){const f=this.store.data.width||this.store.options.width,p=this.store.data.height||this.store.options.height;if(f&&p){let m={x:this.store.data.origin.x,y:this.store.data.origin.y,width:f*this.store.data.scale,height:p*this.store.data.scale};this.activeRect.xm.x+m.width&&(this.activeRect.width=this.activeRect.width-(this.activeRect.x+this.activeRect.width-(m.x+m.width)),this.activeRect.x=m.x+m.width-this.activeRect.width,this.activeRect.ex=this.activeRect.x+this.activeRect.width),this.activeRect.y+this.activeRect.height>m.y+m.height&&(this.activeRect.height=this.activeRect.height-(this.activeRect.y+this.activeRect.height-(m.y+m.height)),this.activeRect.y=m.y+m.height-this.activeRect.height,this.activeRect.ey=this.activeRect.y+this.activeRect.height)}}ro(this.activeRect);const h=this.activeRect.width/o,d=this.activeRect.height/l;this.store.active.forEach((f,p)=>{f.calculative.worldRect.x=this.activeInitPos[p].x*this.activeRect.width+this.activeRect.x,f.calculative.worldRect.y=this.activeInitPos[p].y*this.activeRect.height+this.activeRect.y,f.calculative.worldRect.width*=h,f.calculative.iconWidth&&(f.calculative.iconWidth*=h),f.calculative.worldRect.height*=d,f.calculative.iconHeight&&(f.calculative.iconHeight*=d),Go(f.calculative.worldRect),ro(f.calculative.worldRect),this.updatePenRect(f,{worldRectIsReady:!0}),this.execPenResize(f),this.updateLines(f)}),this.getSizeCPs(),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),this.render(),this.store.emitter.emit("resizePens",this.store.active),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:ur.Update,pens:bt(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0},200)}movePens(e){var o,l;if(!this.activeRect||this.store.data.locked)return;if(!this.initActiveRect){this.initActiveRect=bt(this.activeRect);return}if(!this.store.options.moveConnectedLine&&!this.canMoveLine&&this.store.active.length===1&&((o=this.store.active[0].anchors[0])!=null&&o.connectTo||(l=this.store.active[0].anchors[this.store.active[0].anchors.length-1])!=null&&l.connectTo)||(this.movingPens||(this.initMovingPens(),this.store.active.forEach(c=>{pB(c,!1)}),this.store.hover=void 0),!this.mouseDown))return;let t=e.x-this.mouseDown.x,i=e.y-this.mouseDown.y;e.shiftKey&&!e.ctrlKey&&(i=0),e.ctrlKey&&(t=0);const r=bt(this.initActiveRect);lS(r,t,i);let n=!1;if(this.store.options.strictScope){const c=this.store.data.width||this.store.options.width,u=this.store.data.height||this.store.options.height;if(c&&u){let h={x:this.store.data.origin.x,y:this.store.data.origin.y,width:c*this.store.data.scale,height:u*this.store.data.scale};r.xh.x+h.width&&(r.x=h.x+h.width-r.width,n=!0),r.y+r.height>h.y+h.height&&(r.y=h.y+h.height-r.height,n=!0)}}const a={x:r.x-this.activeRect.x,y:r.y-this.activeRect.y};if(!this.store.options.disableDock&&!n){this.clearDock();const c=this.customMoveDock||npt;this.dock=c(this.store,r,this.movingPens,a);const{xDock:u,yDock:h}=this.dock;let d;u&&(a.x+=u.step,d=this.store.pens[u.penId],d.calculative.isDock=!0),h&&(a.y+=h.step,d=this.store.pens[h.penId],d.calculative.isDock=!0)}this.translatePens(this.movingPens,a.x,a.y,!0)}changeIdsByMoving(e,t){e.id+=Td,e.parentId&&t.find(i=>i.id===e.parentId)&&(e.parentId+=Td),e.children&&(e.children=e.children.map(i=>i+Td)),e.connectedLines&&(e.connectedLines=e.connectedLines.map(i=>(t.find(r=>r.id===i.lineId)&&(i.lineId+=Td),i))),e.type&&e.calculative.worldAnchors&&(e.calculative.worldAnchors=e.calculative.worldAnchors.map(i=>(i.connectTo&&t.find(r=>r.id===i.connectTo)&&(i.connectTo+=Td),i)))}initMovingPens(){var i,r;if(!this.store.options.moveConnectedLine&&!this.canMoveLine)for(let n=0;n{this.changeIdsByMoving(n,t),this.store.pens[n.id]=n,n.calculative.canvas=this;const a={globalAlpha:.5};n.lineWidth===0&&(a.lineWidth=1),(n.name.endsWith("Dom")||xNe.includes(n.name)||this.store.options.domShapes.includes(n.name)||n.image)&&(a.name="rectangle",a.onDestroy=void 0),this.updateValue(n,a),n.calculative.image=void 0})}moveLineAnchor(e,t){var o,l,c,u,h;if(!this.activeRect||this.store.data.locked)return;if(this.initPens||(this.initPens=bt(this.store.active,!0)),(o=this.store.activeAnchor)!=null&&o.connectTo){const d=this.store.pens[this.store.activeAnchor.connectTo];I5(d,HC(d,this.store.activeAnchor.anchorId),this.store.pens[this.store.activeAnchor.penId],this.store.activeAnchor)}let i=(l=this.store.activeAnchor)==null?void 0:l.id,r=(u=(c=this.store.pens[this.store.activeAnchor.penId])==null?void 0:c.connectedLines)==null?void 0:u.filter(d=>d.anchor===i);r&&r.length>0&&r.forEach(d=>{const f=this.store.pens[d.lineId];I5(this.store.pens[this.store.activeAnchor.penId],this.store.activeAnchor,f,HC(f,d.lineAnchor))});const n=this.store.active[0];rl(n);const a=Dn(n);if(n.lineName==="polyline"&&!t.shiftKey)r0t(n,this.store.activeAnchor,e);else{let d=0,f=0;if(n.lineName==="line"){let p=n.calculative.worldAnchors.findIndex(g=>g.id===this.store.activeAnchor.id);p===0&&(p=2);let m=n.calculative.worldAnchors[p-1];if(t.ctrlKey&&t.shiftKey){let g=bt(e);this.getSpecialAngle(g,m),d=g.x-this.store.activeAnchor.x,f=g.y-this.store.activeAnchor.y}else if(!t.ctrlKey&&t.shiftKey){let g={x:e.x,y:m.y};d=g.x-this.store.activeAnchor.x,f=g.y-this.store.activeAnchor.y}else if(t.ctrlKey&&!t.shiftKey){let g={x:m.x,y:e.y};d=g.x-this.store.activeAnchor.x,f=g.y-this.store.activeAnchor.y}else d=e.x-this.store.activeAnchor.x,f=e.y-this.store.activeAnchor.y}else!t.ctrlKey&&t.shiftKey?(d=e.x-this.store.activeAnchor.x,f=0):t.ctrlKey&&!t.shiftKey?(d=0,f=e.y-this.store.activeAnchor.y):(d=e.x-this.store.activeAnchor.x,f=e.y-this.store.activeAnchor.y);BB(this.store.activeAnchor,d,f),this.store.hover&&this.store.hoverAnchor&&this.store.hoverAnchor.penId!==this.store.activeAnchor.penId&&(this.store.hoverAnchor.type===WC.Line?(d=e.x-this.store.activeAnchor.x,f=e.y-this.store.activeAnchor.y,$X(this.store.activeAnchor,this.store.hoverAnchor,this.store)):(d=this.store.hoverAnchor.x-this.store.activeAnchor.x,f=this.store.hoverAnchor.y-this.store.activeAnchor.y),BB(this.store.activeAnchor,d,f),a.prev=void 0,n.lineName!=="polyline"&&((h=this[n.lineName])==null||h.call(this,this.store,n)))}this.patchFlagsLines.add(n),this.store.path2dMap.set(n,Lr.path2dDraws[n.name](n)),this.render(),this.store.active[0].calculative&&(this.store.active[0].calculative.gradientAnimatePath=void 0),this.store.emitter.emit("moveLineAnchor",{pen:this.store.active[0],anchor:this.store.activeAnchor}),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:ur.Update,pens:bt(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0},500)}moveLineAnchorPrev(e){if(!this.activeRect||this.store.data.locked||!this.store.activeAnchor)return;if(this.initPens||(this.initPens=bt(this.store.active,!0)),this.store.activeAnchor.prev.x=e.x,this.store.activeAnchor.prev.y=e.y,this.store.activeAnchor.next){if(!this.store.activeAnchor.prevNextType)this.store.activeAnchor.next.x=e.x,this.store.activeAnchor.next.y=e.y,Pa(this.store.activeAnchor.next,180,this.store.activeAnchor);else if(this.store.activeAnchor.prevNextType===q5.Bilateral&&this.prevAnchor){const i=a0(e,this.store.activeAnchor),r=a0(this.prevAnchor,this.store.activeAnchor);this.store.activeAnchor.next.x=this.nextAnchor.x,this.store.activeAnchor.next.y=this.nextAnchor.y,Pa(this.store.activeAnchor.next,i-r,this.store.activeAnchor)}}const t=this.store.active[0];this.patchFlagsLines.add(t),this.store.path2dMap.set(t,Lr.path2dDraws[t.name](t)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:ur.Update,pens:bt(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0},200)}moveLineAnchorNext(e){if(!this.activeRect||this.store.data.locked||!this.store.activeAnchor)return;if(this.initPens||(this.initPens=bt(this.store.active,!0)),this.store.activeAnchor.next.x=e.x,this.store.activeAnchor.next.y=e.y,this.store.activeAnchor.prev){if(!this.store.activeAnchor.prevNextType)this.store.activeAnchor.prev.x=e.x,this.store.activeAnchor.prev.y=e.y,Pa(this.store.activeAnchor.prev,180,this.store.activeAnchor);else if(this.store.activeAnchor.prevNextType===q5.Bilateral&&this.nextAnchor){const i=a0(e,this.store.activeAnchor),r=a0(this.nextAnchor,this.store.activeAnchor);this.store.activeAnchor.prev.x=this.prevAnchor.x,this.store.activeAnchor.prev.y=this.prevAnchor.y,Pa(this.store.activeAnchor.prev,i-r,this.store.activeAnchor)}}const t=this.store.active[0];this.patchFlagsLines.add(t),this.store.path2dMap.set(t,Lr.path2dDraws[t.name](t)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:ur.Update,pens:bt(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0},200)}async setAnchor(e){var r;const t=[bt(this.store.hover,!0)],i=this.store.hover;if(this.store.hoverAnchor){if(this.beforeRemoveAnchor&&!await this.beforeRemoveAnchor(i,this.store.hoverAnchor))return;i.type===Kn.Line&&((r=i.calculative.worldAnchors)==null?void 0:r.length)<=2?this.delete([i]):(Yft(i,this.store.hoverAnchor),i.type===Kn.Line&&this.initLineRect(i)),this.store.hoverAnchor=void 0,this.store.activeAnchor=void 0,this.externalElements.style.cursor="default"}else if(i){if(this.beforeAddAnchor&&!await this.beforeAddAnchor(i,this.store.pointAt))return;if(i.type===Kn.Line){this.store.activeAnchor=Xft(i,this.store.pointAt,this.store.pointAtIndex),this.initLineRect(i);const n={x:e.x,y:e.y};this.getHover(n)}else{const n={id:fs(),x:e.x,y:e.y};this.store.activeAnchor=jft(i,n)}}this.hotkeyType=ia.None,this.render(),i&&this.pushHistory({type:ur.Update,pens:[bt(i,!0)],initPens:t})}checkDisconnect(e,t){if(e.id.indexOf(Td)>0){const i=e.id;e=this.store.pens[i.replace(Td,"")]}e.anchors.forEach(i=>{if(i.connectTo&&!t.find(r=>r.id===i.connectTo||r.id===i.connectTo+Td)){const r=this.store.pens[i.connectTo];if(!r||r.type)return;I5(r,HC(r,i.anchorId),e,i)}})}translatePens(e=this.store.active,t,i,r){if(!e||!e.length||e.some(l=>{if(l.locked>=qs.DisableMove)return!0}))return;const a=!r&&bt(e,!0);this.activeRect&&lS(this.activeRect,t,i);const o=this.getAllByPens(e);e.forEach(l=>{var c,u;if(!(l.locked>=qs.DisableMove)){if(l.type===Kn.Line){if(!this.store.options.moveConnectedLine&&!this.canMoveLine||l.isRuleLine)return;eEe(l,t,i),this.checkDisconnect(l,o),this.store.path2dMap.set(l,Lr.path2dDraws[l.name](l)),r||(this.initLineRect(l),(c=l.connectedLines)==null||c.forEach(h=>{const d=this.store.pens[h.lineId];this.initLineRect(d)}))}else lS(l.calculative.worldRect,t,i),this.updatePenRect(l,{worldRectIsReady:!0}),l.calculative.x=l.x,l.calculative.y=l.y,l.calculative.initRect&&(l.calculative.initRect.x=l.calculative.x,l.calculative.initRect.y=l.calculative.y,l.calculative.initRect.ex=l.calculative.x+l.calculative.width,l.calculative.initRect.ey=l.calculative.y+l.calculative.height);this.updateLines(l),(u=l.onMove)==null||u.call(l,l)}}),this.activeRect&&this.getSizeCPs(),this.render(),this.tooltip.translate(t,i),r||(this.pushHistory({type:ur.Update,pens:bt(e,!0),initPens:a}),this.initImageCanvas(e),this.initTemplateCanvas(e),this.store.emitter.emit("translatePens",e)),this.store.emitter.emit("translatingPens",e)}templateTranslatePens(e=this.store.active,t,i){if(!e||!e.length)return;const r=this.getAllByPens(e);e.forEach(n=>{var a;if(n.type===Kn.Line){if(!this.store.options.moveConnectedLine&&!this.canMoveLine)return;eEe(n,t,i),this.checkDisconnect(n,r),this.store.path2dMap.set(n,Lr.path2dDraws[n.name](n))}else lS(n.calculative.worldRect,t,i),this.updatePenRect(n,{worldRectIsReady:!0}),n.calculative.x=n.x,n.calculative.y=n.y,n.calculative.initRect&&(n.calculative.initRect.x=n.calculative.x,n.calculative.initRect.y=n.calculative.y,n.calculative.initRect.ex=n.calculative.x+n.calculative.width,n.calculative.initRect.ey=n.calculative.y+n.calculative.height);(a=n.onMove)==null||a.call(n,n)})}calcAutoAnchor(e,t,i,r){const n=rl(e),a=Dn(e),o=R5(i,t===n?a:n);o&&(t.x=o.x,t.y=o.y,t.prev=void 0,t.next=void 0,r?r.anchor=o.id:Zc(i,o,e,t),this[e.lineName]&&this[e.lineName](this.store,e),this.store.path2dMap.set(e,Lr.path2dDraws.line(e)),this.initLineRect(e))}restoreNodeAnimate(e){var t,i;if(e.calculative.initRect){if(e.keepAnimateState)for(const r in e)e.calculative[r]!==void 0&&r!=="x"&&r!=="y"&&r!=="width"&&r!=="height"&&r!=="initRect"&&(typeof e[r]!="object"||r==="lineDash")&&(r==="fontSize"||r==="lineWidth"?e[r]=e.calculative[r]/e.calculative.canvas.store.data.scale:e[r]=e.calculative[r]);else{const r=e.calculative.initRect.rotate-e.calculative.rotate;for(const a in e)a!=="x"&&a!=="y"&&a!=="width"&&a!=="height"&&a!=="initRect"&&a!=="rotate"&&(typeof e[a]!="object"||a==="lineDash")&&(e.calculative[a]=e[a]);(t=e.children)!=null&&t.length?r&&WNe(e,r,e.calculative.worldRect):e.calculative.rotate=e.rotate;const n=bt(this.store.animateMap.get(e));n&&(n.id=e.id,this.parent.setValue(n,{doEvent:!1,render:!0,history:!1})),e.calculative.worldRect=e.calculative.initRect}this.updatePenRect(e,{worldRectIsReady:!0}),this.updateLines(e),e.image&&e.name!=="gif"&&(this.canvasImage.init(),this.canvasImageBottom.init()),e.calculative.text!==e.text&&(e.calculative.text=e.text,iz(e)),(i=this.store.active)!=null&&i.length&&this.calcActiveRect(),e.calculative.initRect=void 0}}updateLines(e,t){var i;(i=e.children)==null||i.forEach(r=>{const n=this.store.pens[r];n&&this.updateLines(n,t)}),e.connectedLines&&e.connectedLines.forEach((r,n)=>{const a=this.store.pens[r.lineId];if(!a||a.calculative.active)return;const o=HC(a,r.lineAnchor);if(!o)return;if(!o.connectTo){e.connectedLines.splice(n,1);return}if(a.autoFrom){const d=rl(a);d.id===o.id&&this.calcAutoAnchor(a,d,e,r)}if(a.autoTo){const d=Dn(a);d.id===o.id&&this.calcAutoAnchor(a,d,e,r)}const l=HC(e,r.anchor);if(!l)return;let c=e.rotate;e.flipX&&(c*=-1),e.flipY&&(c*=-1);let u=o.distance*this.store.data.scale*Math.cos((c+l.rotate)/180*Math.PI)||0,h=o.distance*this.store.data.scale*Math.sin((c+l.rotate)/180*Math.PI)||0;if(e.flipX&&(u=-u),e.flipY&&(h=-h),BB(o,l.x-o.x+u,l.y-o.y+h),this.store.options.autoPolyline&&!this.autoPolylineFlag&&a.autoPolyline!==!1&&a.lineName==="polyline"){let d=rl(a),f=Dn(a),p=!1;d.id===o.id?(d=o,p=!0):f.id===o.id&&(f=o,p=!0),p&&(a.calculative.worldAnchors=[d,f],a.calculative.activeAnchor=d,this.polyline(this.store,a,f),this.initLineRect(a))}this.store.path2dMap.set(a,Lr.path2dDraws[a.name](a)),this.patchFlagsLines.add(a),a.calculative.gradientSmooth&&(a.calculative.gradientAnimatePath=Ume(a)),t&&sue(a)})}calcActiveRect(){const e=this.store.active.filter(t=>(!t.locked||t.locked{Pa(r,t,i.center)}),this.initLineRect(e),GQ(e)):(e.calculative.rotate?e.calculative.rotate+=t:e.calculative.rotate=t,Pa(e.calculative.worldRect.center,t,i.center),e.parentId?(e.calculative.worldRect.x=e.calculative.worldRect.center.x-e.calculative.worldRect.width/2,e.calculative.worldRect.y=e.calculative.worldRect.center.y-e.calculative.worldRect.height/2,e.x=(e.calculative.worldRect.x-i.x)/i.width,e.y=(e.calculative.worldRect.y-i.y)/i.height):(e.x=e.calculative.worldRect.center.x-e.width/2,e.y=e.calculative.worldRect.center.y-e.height/2),e.rotate=e.calculative.rotate,this.updatePenRect(e),e.children&&e.children.forEach(r=>{const n=this.store.pens[r];this.rotatePen(n,t,e.calculative.worldRect)}))}nextAnimate(e){if(!e)return;this.store.emitter.emit("animateEnd",e);let t;e.nextAnimate&&(t=this.store.data.pens.filter(i=>i.id===e.nextAnimate||i.tags&&i.tags.indexOf(e.nextAnimate)>-1)),t&&(t.forEach(i=>{var r,n,a,o,l;if(i.calculative.pause){const c=Date.now()-i.calculative.pause;i.calculative.pause=void 0,i.calculative.frameStart+=c,i.calculative.frameEnd+=c}else if(i.name==="video")i.calculative.media.currentTime=0,(r=i.calculative.media)==null||r.play(),(n=i.onStartVideo)==null||n.call(i,i);else if(i.type||(a=i.frames)!=null&&a.length||i.animations&&i.animations.length){if(i.type){if((l=i.animations)!=null&&l.length){const c=bt(i.animations[0]);delete c.name,c.currentAnimation=0,this.parent.setValue({id:i.id,...c},{doEvent:!1,history:!1})}}else{if(!i.frames&&i.animations&&i.animations.length){let c=(o=i.animations)==null?void 0:o.findIndex(d=>d.autoPlay),u=c===-1?0:c;const h=bt(i.animations[u]);delete h.name,h.currentAnimation=u,!i.type&&h.frames&&(h.showDuration=this.parent.calcAnimateDuration(h)),this.parent.setValue({id:i.id,...h},{doEvent:!1,history:!1})}this.store.animateMap.set(i,this.getFrameProps(i))}this.store.animates.add(i)}}),this.animate())}getFrameProps(e){let t={};return e.frames&&e.frames.forEach(i=>{for(let r in i)!["duration","x","y","width","height","rotate"].includes(r)&&!t[r]&&(t[r]=e[r])}),t}animate(){this.animateRendering||requestAnimationFrame(()=>{const e=Date.now();if(e-this.lastAnimateRender0&&this.animate();return}this.lastAnimateRender=e,this.animateRendering=!0;const t=[];let i=!1;for(const r of this.store.animates)if(!r.calculative.pause){if(r.calculative.active&&!r.type&&!this.movingPens&&(i=!0),!r.type)Qft(r,e)?r.calculative.patchFlags&&(ro(r.calculative.worldRect),this.updatePenRect(r,{worldRectIsReady:!0,playingAnimate:!0})):(requestAnimationFrame(()=>{this.restoreNodeAnimate(r)}),t.push(r),this.nextAnimate(r)),this.updateLines(r,!0);else if(!Zft(r)){if(r.keepAnimateState){for(const n in r)r.calculative[n]!==void 0&&n!=="length"&&(typeof r[n]!="object"||n==="lineDash")&&(n==="lineWidth"?r[n]=r.calculative[n]/r.calculative.canvas.store.data.scale:r[n]=r.calculative[n]);GQ(r)}else for(const n in r)(typeof r[n]!="object"||n==="lineDash")&&(n==="lineWidth"?r.calculative[n]=r[n]*r.calculative.canvas.store.data.scale:r.calculative[n]=r[n]);t.push(r),this.nextAnimate(r)}this.patchFlags=!0}i&&this.calcActiveRect(),t.forEach(r=>{this.store.animates.delete(r)}),this.render(!1),this.animateRendering=!1,this.animate()})}get clipboardName(){return"meta2d-clipboard"}async copy(e,t=!0){const i=fs(),{origin:r,scale:n}=this.store.data;this.store.clipboard=void 0,localStorage.removeItem(this.clipboardName),sessionStorage.setItem("page",i);let a=this.getAllByPens(bt(e||this.store.active,!0));a.forEach(l=>{l.copyIndex=this.store.data.pens.findIndex(c=>c.id===l.id),l.pathId&&(l.path=this.store.data.paths[l.pathId])}),a.sort((l,c)=>l.copyIndex-c.copyIndex);const o={meta2d:!0,pens:a,origin:bt(r),scale:n,page:i,initRect:bt(this.activeRect),offset:10,mousePos:bt(this.mousePos)};if(navigator.clipboard&&!this.store.options.disableClipboard&&!navigator.userAgent.includes("Firefox"))try{await navigator.clipboard.writeText(JSON.stringify(o))}catch{localStorage.setItem(this.clipboardName,JSON.stringify(o))}else localStorage.setItem(this.clipboardName,JSON.stringify(o));t&&this.store.emitter.emit("copy",o.pens)}cut(e){this.copy(e,!1),this.delete(e),this.store.emitter.emit("cut",e)}async paste(){var l,c;let e,t;if(navigator.clipboard&&!this.store.options.disableClipboard&&!navigator.userAgent.includes("Firefox"))try{e=await((l=navigator.clipboard)==null?void 0:l.readText())}catch{e=localStorage.getItem(this.clipboardName)}else e=localStorage.getItem(this.clipboardName);if(e){try{t=JSON.parse(e)}catch(u){console.warn("剪切板数据不是json",u.message);return}if(!t||!t.meta2d)return}else return;if(this.beforeAddPens&&await this.beforeAddPens(t.pens)!=!0)return;let i,r;this.store.clipboard&&(i=this.store.clipboard.offset+10,r=this.store.clipboard.pos),this.store.clipboard=bt(t);const n=sessionStorage.getItem("page"),a=this.store.data.scale;if(this.store.clipboard.mousePos&&(Math.abs(this.store.clipboard.mousePos.x-this.mousePos.x)>100*a||Math.abs(this.store.clipboard.mousePos.y-this.mousePos.y)>100*a)){const u=(a-this.store.clipboard.scale)*this.store.clipboard.initRect.width/2,h=(a-this.store.clipboard.scale)*this.store.clipboard.initRect.height/2;this.store.clipboard.pos={x:this.mousePos.x-u,y:this.mousePos.y-h},this.store.clipboard.offset=0}else n!==t.page?(this.store.clipboard.pos={x:this.mousePos.x,y:this.mousePos.y},this.store.clipboard.offset=0):this.pasteOffset?(i&&(this.store.clipboard.offset=i),r&&(this.store.clipboard.pos=r)):(this.store.clipboard.offset=0,this.pasteOffset=!0);(c=this.keyOptions)!=null&&c.F||this.store.clipboard.pens.forEach(u=>{delete u.copyIndex});const o=this.store.clipboard.pens.filter(u=>!u.parentId);for(const u of o)this.pastePen(u,void 0);sessionStorage.setItem("page",t.page),this.active(o),this.pushHistory({type:ur.Add,pens:this.store.clipboard.pens}),this.render(),this.store.emitter.emit("add",this.store.clipboard.pens),this.store.emitter.emit("paste",this.store.clipboard.pens)}getAllByPens(e){const t=[];for(const i of e)t.push(...bt(S1(i,this.store),!0));return t.concat(e)}getAllFollowersByPens(e,t=!0){const i=e;for(const r of e){let n=Bme(r,this.store);t&&(n=bt(n,!0));for(const a of n)i.find(o=>o.id===a.id)||i.push(a)}return i}setFollowers(e=this.store.active){if(e)if(e.length<2)e[0].followers=[];else{let t=e.map(r=>r.id);t.pop();const i=e[e.length-1];i.followers?t.forEach(r=>{i.followers.includes(r)||i.followers.push(r)}):i.followers=t}}changeLineAnchors(e,t,i){if(Array.isArray(t.connectedLines))for(let r=0;ro.id===n);if(a){const o=a.anchors[0],l=a.anchors[a.anchors.length-1];o.connectTo===e&&(o.connectTo=t.id),l.connectTo===e&&(l.connectTo=t.id)}else t.connectedLines.splice(r,1),r--}}changeNodeConnectedLine(e,t,i){var o;const r=t.anchors[0],n=t.anchors[t.anchors.length-1],a=[r,n];for(const l of a){const c=l.connectTo;if(c){const u=i.find(h=>h.id===c);u?(o=u.connectedLines)==null||o.forEach(h=>{h.lineId===e&&(h.lineId=t.id,h.lineAnchor=l.id)}):(l.connectTo=void 0,l.prev&&(l.prev.connectTo=void 0),l.next&&(l.next.connectTo=void 0))}}}async delete(e=this.store.active,t=!1,i=!0){if(!e||!e.length||this.beforeRemovePens&&await this.beforeRemovePens(e)!=!0||(t||(e=e.filter(n=>!n.locked)),!e||!e.length))return;const r=[];if(this._del(e,r,t),this.initImageCanvas(r),this.initTemplateCanvas(r),this.inactive(),this.clearHover(),this.render(),i){if(r.length===0)return;this.pushHistory({type:ur.Delete,pens:r})}this.store.emitter.emit("delete",e)}_del(e,t,i){e&&e.forEach(r=>{if(r.type&&(r.lastConnected={}),r.parentId)if(this.getLockedParent(r)){console.warn("父节点锁定");return}else{const a=Uf(r),o=a.children.indexOf(r.id);a.children.splice(o,1),t&&this.getDelPens(r,t),this.delForce(r)}else{if(!i&&r.locked)return;t&&this.getDelPens(r,t),this.delForce(r)}})}getDelPens(e,t){if(!e)return;if(this.store.data.pens.findIndex(r=>r.id===e.id)>-1){const r=this.store.pens[e.id];r&&r.calculative&&(r.calculative.active=void 0),t.push(r)}e.children&&e.children.forEach(r=>{this.getDelPens(this.store.pens[r],t)})}getLockedParent(e){if(!e.parentId)return!1;const t=Uf(e);if(t.locked)return t;this.getLockedParent(t)}delForce(e){var i;if(!e)return;const t=this.store.data.pens.findIndex(r=>r.id===e.id);t>-1&&(this.delConnectedLines(this.store.data.pens[t]),this.store.data.pens.splice(t,1),this.store.pens[e.id]=void 0,delete this.store.pens[e.id],e.pathId&&delete this.store.data.paths[e.pathId]),this.store.animates.delete(e),this.store.animateMap.delete(e),e.children&&e.children.forEach(r=>{this.delForce(this.store.pens[r])}),(i=e.onDestroy)==null||i.call(e,e)}delConnectedLines(e){var t;if(e.connectedLines)for(let i=0;il.id===n);(o==null?void 0:o.connectTo)===e.id&&(o.connectTo=void 0,o.anchorId=void 0,o.prev&&(o.prev.connectTo=void 0),o.next&&(o.next.connectTo=void 0)),o=HC(a,n),o&&(o.connectTo=void 0,o.anchorId=void 0,o.prev&&(o.prev.connectTo=void 0),o.next&&(o.next.connectTo=void 0))}}e.type&&((t=e.calculative.worldAnchors)==null||t.forEach((i,r)=>{var a;if(!i.connectTo)return;const n=this.store.pens[i.connectTo];n&&((a=n.calculative.worldAnchors)==null||a.forEach(o=>{I5(n,o,e,i)}))}))}convertSpecialCharacter(e){var t={lt:"<",gt:">",nbsp:" ",amp:"&",quot:'"'};return e.replace(/&(lt|gt|nbsp|amp|quot);/gi,function(i,r){return t[r]})}createInput(){this.inputParent.classList.add("meta2d-input"),this.inputDiv.classList.add("input-div"),this.inputParent.appendChild(this.inputDiv),this.dropdown.onmouseleave=()=>{this.store.hover=null},this.inputParent.appendChild(this.dropdown),this.externalElements.appendChild(this.inputParent),this.inputParent.onmousedown=this.stopPropagation,this.inputDiv.onmousedown=this.stopPropagation,this.inputDiv.contentEditable="false",this.dropdown.onmousedown=this.stopPropagation;let e;for(let t=0;t{if(navigator.userAgent.includes("Firefox")){if(!t.target.innerText){let i=this.inputDiv.offsetWidth/2;window.getComputedStyle(this.inputDiv,null).textAlign!=="center"&&(i=0),this.inputDiv.innerHTML=`
`}}else if(t.target.innerText)this.inputDiv.style.paddingTop="";else{let i=window.getComputedStyle(this.inputDiv,null);i.justifyContent==="center"&&(this.inputDiv.style.paddingTop=` ${this.inputDiv.offsetHeight/2-parseFloat(i.lineHeight)/2}px`)}},this.inputDiv.onblur=()=>{setTimeout(()=>{this.hideInput()},300)},this.inputDiv.oninput=t=>{const i=this.store.pens[this.inputDiv.dataset.penId];if(i&&i.inputType==="number"){const r=t.target.innerText,n=r.replace(/[^0-9]/g,"");r!==n&&(t.preventDefault(),t.target.innerText=n)}if(navigator.userAgent.includes("Firefox")){if(!t.target.innerText.trim()){let r=this.inputDiv.offsetWidth/2;window.getComputedStyle(this.inputDiv,null).textAlign!=="center"&&(r=0),this.inputDiv.innerHTML=`
`}}else if(t.target.innerText)this.inputDiv.style.paddingTop="";else{let r=window.getComputedStyle(this.inputDiv,null);r.justifyContent==="center"&&(this.inputDiv.style.paddingTop=` ${this.inputDiv.offsetHeight/2-parseFloat(r.lineHeight)/2}px`)}this.store.emitter.emit("input",i)},this.inputDiv.onclick=t=>{t.stopPropagation();const i=this.store.pens[this.inputDiv.dataset.penId];this.dropdown.style.display==="block"?this.dropdown.style.display="none":i!=null&&i.dropdownList&&this.store.data.locked&&(this.dropdown.style.display="block"),this.store.emitter.emit("clickInput",i)},this.inputDiv.onkeyup=t=>{this.setDropdownList(!0);const i=this.store.pens[this.inputDiv.dataset.penId];this.store.emitter.emit("input",{pen:i,text:t.key}),t.stopPropagation()},this.inputDiv.onkeydown=t=>{t.stopPropagation()},this.inputDiv.onmousedown=this.stopPropagation,this.inputDiv.onwheel=t=>{t.stopPropagation()},this.inputDiv.onpaste=t=>{t.preventDefault();let i="";t.clipboardData&&t.clipboardData.getData&&(i=t.clipboardData.getData("text/plain")),document.execCommand("insertHTML",!1,i)}}clearDropdownList(){if(this.dropdown.hasChildNodes())for(let e=0;e{i.style.background=r.dropdownHoverBackground||"#eee",i.style.color=r.dropdownHoverColor||"#bdc7db"},i.onmouseleave=()=>{i.style.background=r.dropdownBackground||"#fff",i.style.color=r.dropdownColor||"#bdc7db"},this.dropdown.appendChild(i)}find(e){return this.store.data.pens.filter(t=>t.id==e||t.tags&&t.tags.indexOf(e)>-1)}findOne(e){return this.store.data.pens.find(t=>t.id==e||t.tags&&t.tags.indexOf(e)>-1)}changePenId(e,t){var r,n,a,o,l,c,u;if(e===t)return;const i=this.store.pens[e];if(i&&!this.store.pens[t]){if(i.id=t,this.store.pens[t]=this.store.pens[e],(r=i.onChangeId)==null||r.call(i,i,e,t),delete this.store.pens[e],i.parentId){const h=this.store.pens[i.parentId],d=(n=h.children)==null?void 0:n.findIndex(f=>f===e);d!==-1&&((a=h.children)==null||a.splice(d,1,t))}(o=i.children)==null||o.forEach(h=>{const d=this.store.pens[h];d.parentId=t}),i.formId&&i.followers.forEach(h=>{const d=this.store.pens[h];d.formId=t}),i.type===Kn.Line?this.changeNodeConnectedLine(e,i,this.store.data.pens):(this.changeLineAnchors(e,i,this.store.data.pens),(l=i.connectedLines)==null||l.forEach(({lineId:h})=>{const d=this.store.pens[h];eP(d)})),(c=i.anchors)==null||c.forEach(h=>h.penId=t),(u=i.calculative.worldAnchors)==null||u.forEach(h=>h.penId=t)}}updateValue(e,t){var p,m;const i=this.getPenRect(e),r=e.name;Object.assign(e,t);const n=r!==e.name;t.newId&&this.changePenId(e.id,t.newId);let a=!1,o=!1,l=!1,c=!1,u=!1,h=!1,d,f=!1;for(const g in t)g.indexOf(".")===-1?(g==="rotate"?e.disableRotate?e.rotate=e.calculative.rotate||0:d=e.calculative.rotate||0:g==="canvasLayer"||g==="isBottom"||g==="showChild"?h=!0:g==="image"&&(f=!0),(typeof e[g]!="object"||g==="lineDash")&&(!e.disableRotate||g!=="rotate")&&(e.calculative[g]=t[g]),Gdt.includes(g)&&(o=!0),["name","borderRadius","lineSmooth","close"].includes(g)&&(a=!0),Wdt.includes(g)&&(u=!0),Kdt.includes(g)&&(l=!0),Hdt.includes(g)&&(c=!0),e.image&&e.name!=="gif"&&["globalAlpha","flipY","flipX","x","y","width","height","iconWidth","iconHeight","imageRatio","iconLeft","iconTop","iconAlign","rotate"].includes(g)&&(f=!0)):(delete e[g],Q$(e,g,t[g])),g.split(".")[0]==="anchors"&&eP(e);if(this.setCalculativeByScale(e),n&&((p=e.onDestroy)==null||p.call(e,e),jdt(e)),u){const g={x:t.x??i.x,y:t.y??i.y,width:t.width??i.width,height:t.height??i.height};this.setPenRect(e,g,!1),this.updateLines(e,!0),this.store.active&&this.store.active.length&&e.id===this.store.active[0].id&&this.calcActiveRect()}else l?this.updatePenRect(e):(o&&L1(e),c&&J6e(this.store.pens,e),a&&Lr.path2dDraws[e.name]&&this.store.path2dMap.set(e,Lr.path2dDraws[e.name](e)));if(d!==void 0){const g=e.calculative.rotate;e.calculative.rotate=d,this.rotatePen(e,g-d,e.calculative.worldRect)}(t.image||t.backgroundImage||t.strokeImage)&&(e.calculative.image=void 0,e.calculative.backgroundImage=void 0,e.calculative.strokeImage=void 0,this.loadImage(e)),t.lineGradientColors&&(e.calculative.lineGradient=void 0,e.calculative.gradientColorStop=void 0),t.gradientColors&&(e.calculative.gradient=void 0,e.calculative.radialGradient=void 0),t.gradientRadius&&(e.calculative.gradient=void 0,e.calculative.radialGradient=void 0),t.animateLineWidth&&(e.calculative.gradientAnimatePath=void 0),t.gradientSmooth&&(e.calculative.gradientAnimatePath=void 0),h?(this.canvasImage.init(),this.canvasImageBottom.init()):f&&(e.canvasLayer===void 0&&(e.canvasLayer=hn.CanvasImageBottom,e.calculative.canvasLayer=hn.CanvasImageBottom),e.canvasLayer===hn.CanvasImageBottom?this.canvasImageBottom.init():e.canvasLayer===hn.CanvasImage&&this.canvasImage.init()),(t.canvasLayer!==void 0||e.canvasLayer===hn.CanvasTemplate)&&this.initTemplateCanvas([e]),t.zIndex!==void 0&&(m=e.calculative.singleton)!=null&&m.div&&Ha(e,e.calculative.singleton.div)}execPenResize(e){var t,i;(t=e.onResize)==null||t.call(e,e),(i=e.children)==null||i.forEach(r=>{const n=this.store.pens[r];n&&this.execPenResize(n)})}setPenRect(e,t,i=!0){if(e.parentId)Object.assign(e,t);else{const{origin:r,scale:n}=this.store.data;e.x=r.x+t.x*n,e.y=r.y+t.y*n,e.width=t.width*n,e.height=t.height*n}this.updatePenRect(e),this.execPenResize(e),i&&this.render()}getPenRect(e,t=this.store.data.origin,i=this.store.data.scale){if(e)return e.parentId?{x:e.x,y:e.y,width:e.width,height:e.height}:{x:(e.x-t.x)/i,y:(e.y-t.y)/i,width:e.width/i,height:e.height/i}}toPng(e=2,t,i=!1,r){const n=Um(this.store.data.pens),a=this.store.data.scale;if(!isFinite(n.width))throw new Error("can not to png, because width is not finite");const o=bt(n),l=this.store.data,c=i&&this.store.bkImg;let u=!1,h=!1;if(c){if(n.x+=l.x,n.y+=l.y,Go(n),ov(n,this.canvasRect,!0))Object.assign(n,this.canvasRect);else{const A=rz([...yv(n),...yv(this.canvasRect)]);Object.assign(n,A)}u=n.x===0,h=n.y===0}const d=this.store.data.width||this.store.options.width,f=this.store.data.height||this.store.options.height;let p=!1;d&&f&&!this.store.data.component&&(p=!0),p&&(n.x=this.store.data.origin.x,n.y=this.store.data.origin.y,n.width=d*this.store.data.scale,n.height=f*this.store.data.scale);const m=bt(n),g=rv(e);n.x-=g[3]*a,n.y-=g[0]*a,n.width+=(g[3]+g[1])*a,n.height+=(g[0]+g[2])*a;const _=(r||1920)/n.width;n.width*=_,n.height*=_,Go(n);const y=document.createElement("canvas");if(y.width=n.width,y.height=n.height,y.width>32767||y.height>32767||!navigator.userAgent.includes("Firefox")&&y.height*y.width>268435456||navigator.userAgent.includes("Firefox")&&y.height*y.width>472907776)throw new Error("can not to png, because the size exceeds the browser limit");const v=y.getContext("2d");v.textBaseline="middle",v.scale(_,_);const x=this.store.data.background||this.store.styles.background;if(x&&p&&(v.save(),v.fillStyle=x,v.fillRect(0,0,m.width+(g[1]+g[3])*a,m.height+(g[0]+g[2])*a),v.restore()),c)if(p)v.drawImage(this.store.bkImg,g[3]*a||0,g[0]*a||0,m.width,m.height);else{const A=n.x<0?-n.x:0,b=n.y<0?-n.y:0;v.drawImage(this.store.bkImg,A,b,this.canvasRect.width,this.canvasRect.height)}if(x&&!p)if(c){const A=n.x<0?-n.x:0,b=n.y<0?-n.y:0;v.save(),v.fillStyle=x,v.fillRect(A,b,this.canvasRect.width,this.canvasRect.height),v.restore()}else v.save(),v.fillStyle=x,v.fillRect(0,0,o.width+(g[3]+g[1])*a,o.height+(g[0]+g[2])*a),v.restore();c?p?v.translate(-n.x,-n.y):v.translate((u?l.x:-o.x)+g[3]*a||0,(h?l.y:-o.y)+g[0]*a||0):v.translate(-n.x,-n.y);for(const A of this.store.data.pens){if(!Z$(A,this.store)||A.visible==!1||A.name==="combine"&&!A.draw)continue;const{active:b}=A.calculative;A.calculative.active=!1,A.calculative.img?$$(v,A):KC(v,A,!0),A.calculative.active=b}if(t){y.toBlob(t);return}return y.toDataURL()}activeToPng(e=2,t){return this.pensToPng(this.store.active,e,t)}pensToPng(e=this.store.active,t=2,i){if(e.length===0)return;const r=this.getAllByPens(e);let n=r.map(f=>f.id);const a=Um(r);if(!isFinite(a.width))throw new Error("can not to png, because width is not finite");const o=bt(a),l=rv(t);a.x-=l[3],a.y-=l[0],a.width+=l[3]+l[1],a.height+=l[0]+l[2],Go(a);const c=(i||a.width)/a.width;a.width*=c,a.height*=c;const u=document.createElement("canvas");if(u.width=a.width,u.height=a.height,u.width>32767||u.height>32767||!navigator.userAgent.includes("Firefox")&&u.height*u.width>268435456||navigator.userAgent.includes("Firefox")&&u.height*u.width>472907776)throw new Error("can not to png, because the size exceeds the browser limit");const h=u.getContext("2d");h.textBaseline="middle",h.scale(c,c);const d=this.store.data.background||this.store.styles.background;d&&(h.save(),h.fillStyle=d,h.fillRect(0,0,o.width+(l[3]+l[1]),o.height+(l[0]+l[2])),h.restore()),h.translate(-o.x+l[3],-o.y+l[0]);for(const f of this.store.data.pens)if(n.includes(f.id)){if(!Z$(f,this.store)||f.visible==!1||f.name==="combine"&&!f.draw)continue;const{active:p}=f.calculative;f.calculative.active=!1,f.calculative.img?$$(h,f):KC(h,f),f.calculative.active=p}return u.toDataURL()}toggleAnchorMode(){var e;if(this.hotkeyType)this.hotkeyType===ia.AddAnchor&&(this.hotkeyType=ia.None,this.store.hoverAnchor?this.externalElements.style.cursor="vertical-text":this.store.hover&&(this.externalElements.style.cursor="move"));else{if(this.store.options.disableAnchor||(e=this.store.hover)!=null&&e.disableAnchor)return;this.hotkeyType=ia.AddAnchor,this.store.hover&&(this.externalElements.style.cursor="pointer")}this.patchFlags=!0}addAnchorHand(){if(this.store.activeAnchor&&this.store.active&&this.store.active.length===1&&this.store.active[0].type){const e=[bt(this.store.active[0],!0)];this.store.activeAnchor.prev?this.store.activeAnchor.next||(this.store.activeAnchor.next={...this.store.activeAnchor.prev},Pa(this.store.activeAnchor.next,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0):(this.store.activeAnchor.next||(this.store.activeAnchor.next={penId:this.store.activeAnchor.penId,x:this.store.activeAnchor.x+50,y:this.store.activeAnchor.y}),this.store.activeAnchor.prev={...this.store.activeAnchor.next},Pa(this.store.activeAnchor.prev,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:ur.Update,pens:[bt(this.store.active[0],!0)],initPens:e})}}removeAnchorHand(){if(this.store.activeAnchor&&this.store.active&&this.store.active.length===1&&this.store.active[0].type){const e=[bt(this.store.active[0],!0)];this.hoverType===pr.LineAnchorPrev?(this.store.activeAnchor.prev=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):this.hoverType===pr.LineAnchorNext?(this.store.activeAnchor.next=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):(this.store.activeAnchor.prev=void 0,this.store.activeAnchor.next=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:ur.Update,pens:[bt(this.store.active[0])],initPens:e})}}toggleAnchorHand(){this.store.active.length===1&&this.store.active[0].type&&this.store.activeAnchor&&(this.store.activeAnchor.prevNextType||(this.store.activeAnchor.prevNextType=q5.Mirror),this.store.activeAnchor.prevNextType=(this.store.activeAnchor.prevNextType+1)%3)}gotoView(e,t){let i=Um(this.store.data.pens);if(!isFinite(i.width))throw new Error("can not move view, because width is not finite");const r=this.store.data.width||this.store.options.width,n=this.store.data.height||this.store.options.height;r&&n&&(i={x:this.store.data.origin.x,y:this.store.data.origin.y,width:r*this.store.data.scale,height:n*this.store.data.scale}),this.store.data.x=this.canvas.clientWidth/2-e*i.width-i.x,this.store.data.y=this.canvas.clientHeight/2-t*i.height-i.y,this.onMovePens(),this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init(),this.render()}showMagnifier(){this.magnifierCanvas.canvas.style.zIndex="100",this.externalElements.style.zIndex="101",this.magnifierCanvas.magnifier=!0,this.magnifierCanvas.updateDomOffscreen(),this.externalElements.style.cursor="default",this.render()}hideMagnifier(){this.magnifierCanvas.canvas.style.zIndex="5",this.externalElements.style.zIndex="5",this.magnifierCanvas.magnifier=!1,this.externalElements.style.cursor="default",this.render()}showFit(){this.store.data.locked=0,this.canvasImage.fitFlag=!0,this.canvasImage.activeFit=void 0,this.canvasImage.currentFit=void 0,this.store.data.fits||(this.store.data.fits=[]),this.store.data.fits.forEach(e=>e.active=!1),this.canvasImage.init(),this.canvasImage.render()}hideFit(){this.canvasImage.fitFlag=!1,this.canvasImage.activeFit=void 0,this.canvasImage.currentFit=void 0,this.canvasImage.init(),this.canvasImage.render()}makeFit(){if(this.dragRect.width<100&&this.dragRect.height<100)return;const e=this.store.data.pens.filter(c=>{if(c.parentId||c.isRuleLine)return!1;if(ov(c.calculative.worldRect,this.dragRect,!0))return c.type===Kn.Line&&!this.store.options.dragAllIn?Fse(c,this.dragRect):!0});if(!e.length)return;const t=this.parent.getRect(e),i=this.store.data.scale,r=this.store.data.width||this.store.options.width,n=this.store.data.height||this.store.options.height;let a=(Math.floor(t.x)-this.store.data.origin.x)/i/r,o=(Math.floor(t.y)-this.store.data.origin.y)/i/n,l={x:a,y:o,width:(Math.ceil(t.width)+1)/i/r,height:(Math.ceil(t.height)+1)/i/n,children:e.map(c=>c.id),id:fs(),active:!0};l.x<-.1&&(l.x=-.1),l.y<-.1&&(l.y=-.1),l.width>.5?(l.left=!0,l.right=!0,l.leftValue=(l.x-0)*i*r,l.rightValue=(1-(l.x+l.width))*i*r):l.x<.5?(l.left=!0,l.leftValue=(l.x-0)*i*r):(l.right=!0,l.rightValue=(1-(l.x+l.width))*i*r),l.leftValue<1&&(l.leftValue=0),l.rightValue<1&&(l.rightValue=0),l.height>.5?(l.top=!0,l.bottom=!0,l.topValue=(l.y-0)*i*n,l.bottomValue=(1-(l.y+l.height))*i*n):l.y<.5?(l.top=!0,l.topValue=(l.y-0)*i*n):(l.bottom=!0,l.bottomValue=(1-(l.y+l.height))*i*n),l.topValue<1&&(l.topValue=0),l.bottomValue<1&&(l.bottomValue=0),this.store.data.fits||(this.store.data.fits=[]),this.store.data.fits.forEach(c=>{c.active=!1}),this.store.data.fits.push(l),this.canvasImage.activeFit=l,this.store.emitter.emit("fit",l),this.canvasImage.init(),this.canvasImage.render()}updateFit(e){const t=this.store.data.scale,i=this.store.data.width||this.store.options.width,r=this.store.data.height||this.store.options.height;let n=(e.x-this.store.data.origin.x)/t/i,a=(e.y-this.store.data.origin.y)/t/r;if(this.canvasImage.currentFit){const o=this.canvasImage.activeFit;if(this.canvasImage.currentFit==="top"){a<-.1&&(a=-.1);let u=a-o.y;if(o.height-=u,o.height<.01){o.height=.01;return}o.y=a}if(this.canvasImage.currentFit==="bottom"&&(a>1.1&&(a=1.1),o.height=a-o.y,o.height<=.01&&(o.height=.01)),this.canvasImage.currentFit==="left"){n<-.1&&(n=-.1);let u=n-o.x;if(o.width-=u,o.width<.01){o.width=.01;return}o.x=n}this.canvasImage.currentFit==="right"&&(n>1.1&&(n=1.1),o.width=n-o.x,o.width<=.01&&(o.width=.01));let l={x:o.x*i*t+this.store.data.origin.x,y:o.y*r*t+this.store.data.origin.y,width:o.width*i*t,height:o.height*r*t};Go(l);const c=this.store.data.pens.filter(u=>{if(u.parentId||u.isRuleLine)return!1;if(ov(u.calculative.worldRect,l,!0))return u.type===Kn.Line&&!this.store.options.dragAllIn?Fse(u,l):!0});o.left=void 0,o.leftValue=void 0,o.right=void 0,o.rightValue=void 0,o.top=void 0,o.topValue=void 0,o.bottom=void 0,o.bottomValue=void 0,o.width>.5?(o.left=!0,o.right=!0,o.leftValue=(o.x-0)*t*i,o.rightValue=(1-(o.x+o.width))*t*i):o.x<.5?(o.left=!0,o.leftValue=(o.x-0)*t*i):(o.right=!0,o.rightValue=(1-(o.x+o.width))*t*i),Math.abs(o.leftValue)<1&&(o.leftValue=0),Math.abs(o.rightValue)<1&&(o.rightValue=0),o.height>.5?(o.top=!0,o.bottom=!0,o.topValue=(o.y-0)*t*r,o.bottomValue=(1-(o.y+o.height))*t*r):o.y<.5?(o.top=!0,o.topValue=(o.y-0)*t*r):(o.bottom=!0,o.bottomValue=(1-(o.y+o.height))*t*r),Math.abs(o.topValue)<1&&(o.topValue=0),Math.abs(o.bottomValue)<1&&(o.bottomValue=0),o.children=c.map(u=>u.id),this.store.emitter.emit("fit",o),this.mouseDown.x=e.x,this.mouseDown.y=e.y,this.canvasImage.init(),this.canvasImage.render()}}updateFitRect(e=this.canvasImage.activeFit){const t=this.store.data.width||this.store.options.width,i=this.store.data.height||this.store.options.height;e.left&&(e.leftValue?e.x=Math.abs(e.leftValue)<1?e.leftValue:e.leftValue/t:e.x=0),e.right&&(e.rightValue?e.width=1-(Math.abs(e.rightValue)<1?e.rightValue:e.rightValue/t)-e.x:e.width=1-e.x),e.top&&(e.topValue?e.y=Math.abs(e.topValue)<1?e.topValue:e.topValue/i:e.y=0),e.bottom&&(e.bottomValue?e.height=1-(Math.abs(e.bottomValue)<1?e.bottomValue:e.bottomValue/i)-e.y:e.height=1-e.y),this.canvasImage.init(),this.canvasImage.render()}deleteFit(e=this.canvasImage.activeFit){if(!e)return;const t=this.store.data.fits.findIndex(i=>i.id===e.id);this.store.data.fits.splice(t,1),this.canvasImage.activeFit=void 0,this.canvasImage.init(),this.canvasImage.render(),this.store.emitter.emit("fit",void 0)}calcuActiveFit(){var o;const e=this.store.data.width||this.store.options.width,t=this.store.data.height||this.store.options.height;let i=(this.mouseDown.x-this.store.data.origin.x)/this.store.data.scale/e,r=(this.mouseDown.y-this.store.data.origin.y)/this.store.data.scale/t,n=-1,a=-1;(o=this.store.data.fits)==null||o.forEach((l,c)=>{l.ex=null,l.ey=null,vy({x:i,y:r},l)&&(n=c),l.active&&(a=c)}),n!==-1&&n!==a?(this.canvasImage.activeFit=this.store.data.fits[n],this.store.data.fits[n].active=!0,a!==-1&&(this.store.data.fits[a].active=!1),this.store.emitter.emit("fit",this.store.data.fits[n])):n===-1&&a!==-1&&(this.store.data.fits[a].active=!1,this.store.emitter.emit("fit",void 0),this.canvasImage.activeFit=null),this.inactive(),this.canvasImage.init(),this.canvasImage.render()}toggleMagnifier(){this.magnifierCanvas.magnifier=!this.magnifierCanvas.magnifier,this.magnifierCanvas.magnifier&&(this.externalElements.style.cursor="default"),this.render()}destroy(){var e,t,i,r;switch(this.scroll&&this.scroll.destroy(),(e=this.tooltip)==null||e.destroy(),(t=this.dialog)==null||t.destroy(),(i=this.title)==null||i.destroy(),(r=this.popconfirm)==null||r.destroy(),this.externalElements.removeEventListener("gesturestart",this.onGesturestart),this.externalElements.ondragover=n=>n.preventDefault(),this.externalElements.ondrop=void 0,this.externalElements.ontouchstart=void 0,this.externalElements.ontouchmove=void 0,this.externalElements.ontouchend=void 0,this.externalElements.onmousedown=void 0,this.externalElements.onmousemove=void 0,this.externalElements.onmouseup=void 0,this.externalElements.onmouseleave=void 0,this.externalElements.ondblclick=void 0,this.store.options.keydown){case fB.Document:document.removeEventListener("keydown",this.onkeydown),document.removeEventListener("keyup",this.onkeyup);break;case fB.Canvas:this.externalElements.removeEventListener("keydown",this.onkeydown),this.externalElements.removeEventListener("keyup",this.onkeyup);break}document.removeEventListener("copy",this.onCopy),document.removeEventListener("cut",this.onCut),document.removeEventListener("paste",this.onPaste),window&&window.removeEventListener("message",this.onMessage),window&&window.removeEventListener("resize",this.onResize),window&&window.removeEventListener("scroll",this.onScroll),this.parentElement.innerHTML=""}}function b0t(s,e){const t=e||new Path2D;s.onDestroy||(s.onDestroy=S0t,s.onMove=xEe,s.onRotate=xEe,s.onMouseEnter=E0t,s.onMouseLeave=T0t,s.onMouseMove=R0t,s.onMouseUp=M0t,s.onInput=C0t),s.formId=s.id;let i=s.calculative.borderRadius||0,r=i;const{x:n,y:a,width:o,height:l,ex:c,ey:u}=s.calculative.worldRect;s.calculative.worldTextRect,i<1&&(i=o*i,r=l*r);let h=i{if(s.followers){let i=s.followers.findIndex(r=>r===t.id);if(i!==-1){const r=s.calculative.canvas.store.pens[t.id+Td];r&&r.calculative&&(ov(r.calculative.worldRect,s.calculative.worldRect,!0)||(s.followers.splice(i,1),delete t.formId))}}})}function M0t(s){const e=s.calculative.canvas.store.active;e&&e.length&&e.forEach(t=>{const i=s.calculative.canvas.store.pens[t.id+Td];if(i&&i.calculative){let r=bt(s.calculative.worldRect);r.x-=1,r.y-=1,r.width+=2,r.height+=2,ov(i.calculative.worldRect,r,!0)&&(s.followers||(s.followers=[]),s.followers.includes(t.id)||s.followers.push(t.id),t.formId=s.id)}})}function R0t(s,e){}function AEe(s,e){if(s.formId&&s.formKey&&s.formValue){const t=s.calculative.canvas.store.pens[s.formId];t&&(t.formData||(t.formData={}),t.formData[s.formKey]=s[s.formValue])}}function I0t(s){const e=s.calculative.canvas.store.pens[s.formId];e.followers.forEach(t=>{const i=s.calculative.canvas.store.pens[t];if(i.formId&&i.formKey&&e.formData[i.formKey]){const r=i[i.formValue];let n="";Array.isArray(r)&&(n=[]),s.calculative.canvas.parent.setValue({id:i.id,[i.formValue]:n},{render:!1,doEvent:!1,history:!1})}}),e.formData={},s.calculative.canvas.parent.render()}const lc={};function P0t(s){s.onDestroy||(s.onDestroy=w0t,s.onMove=bEe,s.onResize=D0t,s.onRotate=bEe,s.onValue=L0t,s.onChangeId=O0t);const e=new Path2D;if(!s.image)return;const i=s.calculative.canvas.store.id+"-"+s.id;if(!lc[i]){const r=new Image;r.crossOrigin="anonymous",r.src=s.image,s.calculative.canvas.parent.store.options.cdn&&!(s.image.startsWith("http")||s.image.startsWith("//")||s.image.startsWith("data:image"))&&(r.src=s.calculative.canvas.parent.store.options.cdn+s.image),lc[i]=r,r.onload=()=>{var n;lc[i]===r&&(s.calculative.img=r,s.calculative.imgNaturalWidth=r.naturalWidth||s.iconWidth,s.calculative.imgNaturalHeight=r.naturalHeight||s.iconHeight,(n=s.calculative.canvas.externalElements)==null||n.parentElement.appendChild(r),Dk(s,r))}}return s.calculative.patchFlags&&lc[i]&&Dk(s,lc[i]),e}function w0t(s){const t=s.calculative.canvas.store.id+"-"+s.id;lc[t]&&(lc[t].remove(),lc[t]=void 0)}function bEe(s){const t=s.calculative.canvas.store.id+"-"+s.id;lc[t]&&Dk(s,lc[t])}function D0t(s){const t=s.calculative.canvas.store.id+"-"+s.id;lc[t]&&Dk(s,lc[t])}function L0t(s){const t=s.calculative.canvas.store.id+"-"+s.id;lc[t]&&(Dk(s,lc[t]),lc[t].getAttribute("src")!==s.image&&(lc[t].src=s.image))}function O0t(s,e,t){const i=s.calculative.canvas.store.id;lc[i+"-"+e]&&(lc[i+"-"+t]=lc[i+"-"+e],delete lc[i+"-"+e])}function Dk(s,e){e.style.objectFit=s.imageRatio?"contain":"fill",Ha(s,e)}function N0t(s,e){return s.onResize||(s.onResize=sFe,s.onValue=F0t),CS(s,e)}function sFe(s){const e=s.anchors.filter(t=>t.flag!==1);nFe(s),s.anchors=s.anchors.concat(...e)}function F0t(s){sFe(s),eP(s)}function nFe(s){const e=[],{x:t,y:i,width:r,height:n}=s,a=B0t(s),o=5;for(let h=0;ht+r-a&&(f=rY(t+r-a,f+a,d,a,-1)),e.push({id:String(e.length),flag:1,penId:s.id,x:(d-t)/r,y:(f-i)/n})}const l=3;for(let h=0;hi+n-a&&(f=iY(f-a,i+n-a,d,a)),e.push({id:String(e.length),flag:1,penId:s.id,x:(f-t)/r,y:(d-i)/n})}const c=5;for(let h=0;ht+r-a&&(f=rY(t+r-a,f-a,d,a)),e.push({id:String(e.length),flag:1,penId:s.id,x:(d-t)/r,y:(f-i)/n})}const u=3;for(let h=0;hi+n-a&&(f=iY(f+a,i+n-a,d,a,-1)),e.push({id:String(e.length),flag:1,penId:s.id,x:(f-t)/r,y:(d-i)/n})}s.anchors=e}function B0t(s){let e=s.calculative.borderRadius||0,t=s.calculative.borderRadius||0;const{width:i,height:r}=s;s.calculative.borderRadius<1&&(e=i*s.calculative.borderRadius,t=r*s.calculative.borderRadius);let n=e({id:r+"",x:t,y:i,penId:s.id}))}function z0t(){return{rectangle:CS,square:zdt,circle:Vdt,svgPath:Tpt,diamond:Mpt,triangle:Rpt,pentagon:Ppt,pentagram:Dpt,hexagon:Opt,leftArrow:Npt,rightArrow:Fpt,twowayArrow:Bpt,message:kpt,cloud:Upt,file:zpt,people:Gpt,line:jpt,iframe:l0t,video:f0t,gif:P0t,mindNode:N0t,mindLine:k0t,mindNode2:CS,form:b0t,combine:CS}}function V0t(){return{triangle:Ipt,pentagon:wpt,pentagram:XNe,mindNode:nFe,mindLine:U0t}}var nc=(s=>(s[s.Link=0]="Link",s[s.SetProps=1]="SetProps",s[s.StartAnimate=2]="StartAnimate",s[s.PauseAnimate=3]="PauseAnimate",s[s.StopAnimate=4]="StopAnimate",s[s.JS=5]="JS",s[s.GlobalFn=6]="GlobalFn",s[s.Emit=7]="Emit",s[s.StartVideo=8]="StartVideo",s[s.PauseVideo=9]="PauseVideo",s[s.StopVideo=10]="StopVideo",s[s.SendPropData=11]="SendPropData",s[s.SendVarData=12]="SendVarData",s[s.Navigator=13]="Navigator",s[s.Dialog=14]="Dialog",s[s.SendData=15]="SendData",s[s.PostMessage=16]="PostMessage",s[s.PostMessageToParent=17]="PostMessageToParent",s[s.Message=18]="Message",s))(nc||{});class G0t{constructor(e){ke(this,"box");ke(this,"boxWidth",320);ke(this,"boxHeight",180);ke(this,"ratio",this.boxWidth/this.boxHeight);ke(this,"padding",5);ke(this,"img");ke(this,"isShow");ke(this,"isDown");ke(this,"view");ke(this,"timer");ke(this,"onMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDown=!0});ke(this,"onMouseMove",e=>{if(e.preventDefault(),e.stopPropagation(),this.isDown)try{this.parent.gotoView(e.offsetX/this.box.clientWidth,e.offsetY/this.box.clientHeight)}catch(t){console.warn(t.message),this.isDown=!1}});ke(this,"onMouseUp",e=>{e.preventDefault(),e.stopPropagation();try{this.parent.gotoView(e.offsetX/this.box.clientWidth,e.offsetY/this.box.clientHeight)}catch(t){console.warn(t.message)}finally{this.isDown=!1}});ke(this,"onWheel",e=>{let t=.015;if(this.parent.store.options.scaleOff)t=this.parent.store.options.scaleOff,e.deltaY>0&&(t=-this.parent.store.options.scaleOff);else if(/mac os /i.test(navigator.userAgent))e.ctrlKey?e.deltaY>0&&(t*=-1):t*=e.wheelDeltaY/240;else{let l=.2;e.deltaY.toString().indexOf(".")!==-1&&(l=.01),e.deltaY>0?t=-l:t=l}let{offsetX:i,offsetY:r}=e;const n=this.parent.store.data.width||this.parent.store.options.width,a=this.parent.store.data.height||this.parent.store.options.height;if(n&&a)i=i/this.boxWidth*n*this.parent.store.data.scale+this.parent.store.data.origin.x+this.parent.store.data.x,r=r/this.boxHeight*a*this.parent.store.data.scale+this.parent.store.data.origin.y+this.parent.store.data.y;else{const o=this.parent.parent.getRect();i=i/this.boxWidth*o.width+o.x+this.parent.store.data.x,r=r/this.boxHeight*o.height+o.y+this.parent.store.data.y}this.parent.scale(this.parent.store.data.scale+t,{x:i,y:r})});var i;this.parent=e,this.box=document.createElement("div"),this.img=new Image,this.view=document.createElement("div"),this.box.appendChild(this.img),this.box.appendChild(this.view),(i=this.parent.externalElements)==null||i.parentElement.appendChild(this.box),this.box.className="meta2d-map",this.box.onmousedown=this.onMouseDown,this.box.onmousemove=this.onMouseMove,this.box.onmouseup=this.onMouseUp,this.box.onwheel=this.onWheel;let t;for(let r=0;r{this.parent.store.bkImg&&(this.img.src=this.parent.toPng(0,void 0,!0))},300)),lS(t,e.x,e.y),t.width/t.height>this.ratio){const h=t.width/this.ratio;t.y-=(h-t.height)/2,t.height=h,Go(t)}else{const h=t.height*this.ratio;t.x-=(h-t.width)/2,t.width=h,Go(t)}const a=this.parent.canvasRect;let o=0,l=0;if(t.x<0)o=-t.x/t.width;else if(t.x+t.width>a.width){let h=0;a.width>t.width&&(h=a.width-t.width),o=(-t.x+h)/t.width}if(t.y<0)l=-t.y/t.height;else if(t.y+t.height>a.height){let h=0;a.height>t.height&&(h=a.height-t.height),l=(-t.y+h)/t.height}const c=a.width>t.width?1:a.width/t.width,u=a.height>t.height?1:a.height/t.height;this.view.style.left=this.padding+o*this.boxWidth+"px",this.view.style.width=c*this.boxWidth+"px",this.view.style.top=this.padding+l*this.boxHeight+"px",this.view.style.height=u*this.boxHeight+"px"}}}function W1(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var aFe={exports:{}};(function(s,e){(function(t){s.exports=t()})(function(){return function(){return function t(i,r,n){function a(c,u){if(!r[c]){if(!i[c]){var h=typeof W1=="function"&&W1;if(!u&&h)return h(c,!0);if(o)return o(c,!0);var d=new Error("Cannot find module '"+c+"'");throw d.code="MODULE_NOT_FOUND",d}var f=r[c]={exports:{}};i[c][0].call(f.exports,function(p){return a(i[c][1][p]||p)},f,f.exports,t,i,r,n)}return r[c].exports}for(var o=typeof W1=="function"&&W1,l=0;l0&&(L.topicAliasMaximum>65535?v("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new c(L.topicAliasMaximum)),this.on("connect",function(){const H=this.queue;v("connect :: sending queued packets"),function j(){const z=H.shift();v("deliver :: entry %o",z);let K=null;if(!z)return void V._resubscribe();K=z.packet,v("deliver :: call _sendPacket for %o",K);let U=!0;K.messageId&&K.messageId!==0&&(V.messageIdProvider.register(K.messageId)||(U=!1)),U?V._sendPacket(K,function(W){z.cb&&z.cb(W),j()}):(v("messageId: %d has already used. The message is skipped and removed.",K.messageId),j())}()}),this.on("close",function(){v("close :: connected set to `false`"),this.connected=!1,v("close :: clearing connackTimer"),clearTimeout(this.connackTimer),v("close :: clearing ping timer"),V.pingTimer!==null&&(V.pingTimer.clear(),V.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),v("close :: calling _setupReconnect"),this._setupReconnect()}),o.call(this),v("MqttClient :: setting up stream"),this._setupStream()}p(R,o),R.prototype._setupStream=function(){const I=this,L=new f,k=h.parser(this.options);let V=null;const H=[];function j(){if(H.length)x(z);else{const U=V;V=null,U()}}function z(){v("work :: getting next packet in queue");const U=H.shift();if(U)v("work :: packet pulled from queue"),I._handlePacket(U,j);else{v("work :: no packets in queue");const W=V;V=null,v("work :: done flag is %s",!!W),W&&W()}}v("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),v("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),k.on("packet",function(U){v("parser :: on packet push to packets array."),H.push(U)}),L._write=function(U,W,Z){V=Z,v("writable stream :: parsing buffer"),k.parse(U),z()},v("_setupStream :: pipe stream to writable stream"),this.stream.pipe(L),this.stream.on("error",function(U){v("streamErrorHandler :: error",U.message),U.code?(v("streamErrorHandler :: emitting error"),I.emit("error",U)):M(U)}),this.stream.on("close",function(){var U;v("(%s)stream :: on close",I.options.clientId),(U=I.outgoing)&&(v("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(U).forEach(function(W){U[W].volatile&&typeof U[W].cb=="function"&&(U[W].cb(new Error("Connection closed")),delete U[W])})),v("stream: emit close to MqttClient"),I.emit("close")}),v("_setupStream: sending packet `connect`");const K=Object.create(this.options);if(K.cmd="connect",this.topicAliasRecv&&(K.properties||(K.properties={}),this.topicAliasRecv&&(K.properties.topicAliasMaximum=this.topicAliasRecv.max)),w(this,K),k.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return I.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"&&w(this,y({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(function(){v("!!connectTimeout hit!! Calling _cleanUp with force `true`"),I._cleanUp(!0)},this.options.connectTimeout)},R.prototype._handlePacket=function(I,L){const k=this.options;if(k.protocolVersion===5&&k.properties&&k.properties.maximumPacketSize&&k.properties.maximumPacketSize0||!z())&&this._storeProcessingQueue.push({invoke:z,cbStorePut:k.cbStorePut,callback:V}),this},R.prototype.subscribe=function(){const I=this,L=new Array(arguments.length);for(let q=0;q0){const ce={qos:ue.qos};K===5&&(ce.nl=ue.nl||!1,ce.rap=ue.rap||!1,ce.rh=ue.rh||0,ce.properties=ue.properties),I._resubscribeTopics[ue.topic]=ce,ae.push(ue.topic)}}),I.messageIdToTopic[ie.messageId]=ae}return I.outgoing[ie.messageId]={volatile:!0,cb:function(ae,ue){if(!ae){const ce=ue.granted;for(let N=0;N0||!Z())&&this._storeProcessingQueue.push({invoke:Z,callback:j}),this},R.prototype.unsubscribe=function(){const I=this,L=new Array(arguments.length);for(let K=0;K0||!z())&&this._storeProcessingQueue.push({invoke:z,callback:V}),this},R.prototype.end=function(I,L,k){const V=this;function H(){v("end :: (%s) :: finish :: calling _cleanUp with force %s",V.options.clientId,I),V._cleanUp(I,()=>{v("end :: finish :: calling process.nextTick on closeStores"),x((function(){v("end :: closeStores: closing incoming and outgoing stores"),V.disconnected=!0,V.incomingStore.close(function(j){V.outgoingStore.close(function(z){if(v("end :: closeStores: emitting end"),V.emit("end"),k){const K=j||z;v("end :: closeStores: invoking callback with args"),k(K)}})}),V._deferredReconnect&&V._deferredReconnect()}).bind(V))},L)}return v("end :: (%s)",this.options.clientId),I!=null&&typeof I=="boolean"||(k=L||M,L=I,I=!1,typeof L!="object"&&(k=L,L=null,typeof k!="function"&&(k=M))),typeof L!="object"&&(k=L,L=null),v("end :: cb? %s",!!k),k=k||M,this.disconnecting?(k(),this):(this._clearReconnect(),this.disconnecting=!0,!I&&Object.keys(this.outgoing).length>0?(v("end :: (%s) :: calling finish in 10ms once outgoing is empty",V.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,H,10))):(v("end :: (%s) :: immediately calling finish",V.options.clientId),H()),this)},R.prototype.removeOutgoingMessage=function(I){const L=this.outgoing[I]?this.outgoing[I].cb:null;return delete this.outgoing[I],this.outgoingStore.del({messageId:I},function(){L(new Error("Message removed"))}),this},R.prototype.reconnect=function(I){v("client reconnect");const L=this,k=function(){I?(L.options.incomingStore=I.incomingStore,L.options.outgoingStore=I.outgoingStore):(L.options.incomingStore=null,L.options.outgoingStore=null),L.incomingStore=L.options.incomingStore||new l,L.outgoingStore=L.options.outgoingStore||new l,L.disconnecting=!1,L.disconnected=!1,L._deferredReconnect=null,L._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=k:k(),this},R.prototype._reconnect=function(){v("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this._setupStream()}),v("client already connected. disconnecting first.")):(v("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const I=this;!I.disconnecting&&!I.reconnectTimer&&I.options.reconnectPeriod>0?(this.reconnecting||(v("_setupReconnect :: emit `offline` state"),this.emit("offline"),v("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),v("_setupReconnect :: setting reconnectTimer for %d ms",I.options.reconnectPeriod),I.reconnectTimer=setInterval(function(){v("reconnectTimer :: reconnect triggered!"),I._reconnect()},I.options.reconnectPeriod)):v("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){v("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(I,L){const k=arguments[2];if(L&&(v("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",L)),v("_cleanUp :: forced? %s",I),I)this.options.reconnectPeriod===0&&this.options.clean&&(V=this.outgoing)&&(v("flush: queue exists? %b",!!V),Object.keys(V).forEach(function(H){typeof V[H].cb=="function"&&(V[H].cb(new Error("Connection closed")),delete V[H])})),v("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const H=y({cmd:"disconnect"},k);v("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(H,A.bind(null,this.stream.end.bind(this.stream)))}var V;this.disconnecting||(v("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this.pingTimer!==null&&(v("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),L&&!this.connected&&(v("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",L),L())},R.prototype._sendPacket=function(I,L,k){v("_sendPacket :: (%s) :: start",this.options.clientId),k=k||M,L=L||M;const V=function(H,j){if(H.options.protocolVersion===5&&j.cmd==="publish"){let z;j.properties&&(z=j.properties.topicAlias);const K=j.topic.toString();if(H.topicAliasSend)if(z){if(K.length!==0&&(v("applyTopicAlias :: register topic: %s - alias: %d",K,z),!H.topicAliasSend.put(K,z)))return v("applyTopicAlias :: error out of range. topic: %s - alias: %d",K,z),new Error("Sending Topic Alias out of range")}else K.length!==0&&(H.options.autoAssignTopicAlias?(z=H.topicAliasSend.getAliasByTopic(K))?(j.topic="",j.properties={...j.properties,topicAlias:z},v("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",K,z)):(z=H.topicAliasSend.getLruAlias(),H.topicAliasSend.put(K,z),j.properties={...j.properties,topicAlias:z},v("applyTopicAlias :: auto assign topic: %s - alias: %d",K,z)):H.options.autoUseTopicAlias&&(z=H.topicAliasSend.getAliasByTopic(K))&&(j.topic="",j.properties={...j.properties,topicAlias:z},v("applyTopicAlias :: auto use topic: %s - alias: %d",K,z)));else if(z)return v("applyTopicAlias :: error out of range. topic: %s - alias: %d",K,z),new Error("Sending Topic Alias out of range")}}(this,I);if(V)L(V);else{if(!this.connected)return I.cmd==="auth"?(this._shiftPingInterval(),void w(this,I,L)):(v("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(I,L,k));switch(this._shiftPingInterval(),I.cmd){case"publish":break;case"pubrel":return void P(this,I,L,k);default:return void w(this,I,L)}switch(I.qos){case 2:case 1:P(this,I,L,k);break;case 0:default:w(this,I,L)}v("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(I,L,k){v("_storePacket :: packet: %o",I),v("_storePacket :: cb? %s",!!L),k=k||M;let V=I;if(V.cmd==="publish"){const H=T(this,V=g(I));if(H)return L&&L(H)}(V.qos||0)===0&&this.queueQoSZero||V.cmd!=="publish"?this.queue.push({packet:V,cb:L}):V.qos>0?(L=this.outgoing[V.messageId]?this.outgoing[V.messageId].cb:null,this.outgoingStore.put(V,function(H){if(H)return L&&L(H);k()})):L&&L(new Error("No connection to broker"))},R.prototype._setupPingTimer=function(){v("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const I=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=m(function(){I._checkPing()},1e3*this.options.keepalive))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){v("_checkPing :: checking ping..."),this.pingResp?(v("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(v("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(I){v("_handleConnack");const L=this.options,k=L.protocolVersion===5?I.reasonCode:I.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,I.properties){if(I.properties.topicAliasMaximum){if(I.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));I.properties.topicAliasMaximum>0&&(this.topicAliasSend=new u(I.properties.topicAliasMaximum))}I.properties.serverKeepAlive&&L.keepalive&&(L.keepalive=I.properties.serverKeepAlive,this._shiftPingInterval()),I.properties.maximumPacketSize&&(L.properties||(L.properties={}),L.properties.maximumPacketSize=I.properties.maximumPacketSize)}if(k===0)this.reconnecting=!1,this._onConnect(I);else if(k>0){const V=new Error("Connection refused: "+C[k]);V.code=k,this.emit("error",V)}},R.prototype._handleAuth=function(I){const L=this.options.protocolVersion,k=L===5?I.reasonCode:I.returnCode;if(L!==5){const H=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+L);return H.code=k,void this.emit("error",H)}const V=this;this.handleAuth(I,function(H,j){if(H)V.emit("error",H);else if(k===24)V.reconnecting=!1,V._sendPacket(j);else{const z=new Error("Connection refused: "+C[k]);H.code=k,V.emit("error",z)}})},R.prototype.handleAuth=function(I,L){L()},R.prototype._handlePublish=function(I,L){v("_handlePublish: packet %o",I),L=L!==void 0?L:M;let k=I.topic.toString();const V=I.payload,H=I.qos,j=I.messageId,z=this,K=this.options,U=[0,16,128,131,135,144,145,151,153];if(this.options.protocolVersion===5){let W;if(I.properties&&(W=I.properties.topicAlias),W!==void 0)if(k.length===0){if(!(W>0&&W<=65535))return v("_handlePublish :: topic alias out of range. alias: %d",W),void this.emit("error",new Error("Received Topic Alias is out of range"));{const Z=this.topicAliasRecv.getTopicByAlias(W);if(!Z)return v("_handlePublish :: unregistered topic alias. alias: %d",W),void this.emit("error",new Error("Received unregistered Topic Alias"));v("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",k=Z,W)}}else{if(!this.topicAliasRecv.put(k,W))return v("_handlePublish :: topic alias out of range. alias: %d",W),void this.emit("error",new Error("Received Topic Alias is out of range"));v("_handlePublish :: registered topic: %s - alias: %d",k,W)}}switch(v("_handlePublish: qos %d",H),H){case 2:K.customHandleAcks(k,V,I,function(W,Z){return W instanceof Error||(Z=W,W=null),W?z.emit("error",W):U.indexOf(Z)===-1?z.emit("error",new Error("Wrong reason code for pubrec")):void(Z?z._sendPacket({cmd:"pubrec",messageId:j,reasonCode:Z},L):z.incomingStore.put(I,function(){z._sendPacket({cmd:"pubrec",messageId:j},L)}))});break;case 1:K.customHandleAcks(k,V,I,function(W,Z){return W instanceof Error||(Z=W,W=null),W?z.emit("error",W):U.indexOf(Z)===-1?z.emit("error",new Error("Wrong reason code for puback")):(Z||z.emit("message",k,V,I),void z.handleMessage(I,function(q){if(q)return L&&L(q);z._sendPacket({cmd:"puback",messageId:j,reasonCode:Z},L)}))});break;case 0:this.emit("message",k,V,I),this.handleMessage(I,L);break;default:v("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(I,L){L()},R.prototype._handleAck=function(I){const L=I.messageId,k=I.cmd;let V=null;const H=this.outgoing[L]?this.outgoing[L].cb:null,j=this;let z;if(H){switch(v("_handleAck :: packet type",k),k){case"pubcomp":case"puback":{const K=I.reasonCode;K&&K>0&&K!==16&&((z=new Error("Publish error: "+C[K])).code=K,H(z,I)),delete this.outgoing[L],this.outgoingStore.del(I,H),this.messageIdProvider.deallocate(L),this._invokeStoreProcessingQueue();break}case"pubrec":{V={cmd:"pubrel",qos:2,messageId:L};const K=I.reasonCode;K&&K>0&&K!==16?((z=new Error("Publish error: "+C[K])).code=K,H(z,I)):this._sendPacket(V);break}case"suback":delete this.outgoing[L],this.messageIdProvider.deallocate(L);for(let K=0;K0)if(this.options.resubscribe)if(this.options.protocolVersion===5){v("_resubscribe: protocolVersion 5");for(let L=0;L0){const I=this._storeProcessingQueue[0];if(I&&I.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.prototype._flushStoreProcessingQueue=function(){for(const I of this._storeProcessingQueue)I.cbStorePut&&I.cbStorePut(new Error("Connection closed")),I.callback&&I.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},i.exports=R}).call(this)}).call(this,t("_process"),typeof Xt<"u"?Xt:typeof self<"u"?self:typeof window<"u"?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(t,i,r){const{Buffer:n}=t("buffer"),a=t("readable-stream").Transform,o=t("duplexify");let l,c,u,h=!1;i.exports=function(d,f){if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");const p=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";(function(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})})(f);const m=function(g,_){const y=g.protocol==="alis"?"wss":"ws";let v=y+"://"+g.hostname+g.path;return g.port&&g.port!==80&&g.port!==443&&(v=y+"://"+g.hostname+":"+g.port+g.path),typeof g.transformWsUrl=="function"&&(v=g.transformWsUrl(v,g,_)),v}(f,d);return(l=f.my).connectSocket({url:m,protocols:p}),c=function(){const g=new a;return g._write=function(_,y,v){l.sendSocketMessage({data:_.buffer,success:function(){v()},fail:function(){v(new Error)}})},g._flush=function(_){l.closeSocket({success:function(){_()}})},g}(),u=o.obj(),h||(h=!0,l.onSocketOpen(function(){u.setReadable(c),u.setWritable(c),u.emit("connect")}),l.onSocketMessage(function(g){if(typeof g.data=="string"){const _=n.from(g.data,"base64");c.push(_)}else{const _=new FileReader;_.addEventListener("load",function(){let y=_.result;y=y instanceof ArrayBuffer?n.from(y):n.from(y,"utf8"),c.push(y)}),_.readAsArrayBuffer(g.data)}}),l.onSocketClose(function(){u.end(),u.destroy()}),l.onSocketError(function(g){u.destroy(g)})),u}},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(t,i,r){const n=t("net"),a=t("debug")("mqttjs:tcp");i.exports=function(o,l){l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost";const c=l.port,u=l.hostname;return a("port %d and host %s",c,u),n.createConnection(c,u)}},{debug:18,net:16}],4:[function(t,i,r){const n=t("tls"),a=t("net"),o=t("debug")("mqttjs:tls");i.exports=function(l,c){c.port=c.port||8883,c.host=c.hostname||c.host||"localhost",a.isIP(c.host)===0&&(c.servername=c.host),c.rejectUnauthorized=c.rejectUnauthorized!==!1,delete c.path,o("port %d host %s rejectUnauthorized %b",c.port,c.host,c.rejectUnauthorized);const u=n.connect(c);function h(d){c.rejectUnauthorized&&l.emit("error",d),u.end()}return u.on("secureConnect",function(){c.rejectUnauthorized&&!u.authorized?u.emit("error",new Error("TLS not authorized")):u.removeListener("error",h)}),u.on("error",h),u}},{debug:18,net:16,tls:16}],5:[function(t,i,r){(function(n){(function(){const{Buffer:a}=t("buffer"),o=t("ws"),l=t("debug")("mqttjs:ws"),c=t("duplexify"),u=t("readable-stream").Transform,h=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],d=n!==void 0&&n.title==="browser"||typeof __webpack_require__=="function";function f(m,g){let _=m.protocol+"://"+m.hostname+":"+m.port+m.path;return typeof m.transformWsUrl=="function"&&(_=m.transformWsUrl(_,m,g)),_}function p(m){const g=m;return m.hostname||(g.hostname="localhost"),m.port||(m.protocol==="wss"?g.port=443:g.port=80),m.path||(g.path="/"),m.wsOptions||(g.wsOptions={}),d||m.protocol!=="wss"||h.forEach(function(_){Object.prototype.hasOwnProperty.call(m,_)&&!Object.prototype.hasOwnProperty.call(m.wsOptions,_)&&(g.wsOptions[_]=m[_])}),g}i.exports=d?function(m,g){let _;l("browserStreamBuilder");const y=function(I){const L=p(I);if(L.hostname||(L.hostname=L.host),!L.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");const k=new URL(document.URL);L.hostname=k.hostname,L.port||(L.port=k.port)}return L.objectMode===void 0&&(L.objectMode=!(L.binary===!0||L.binary===void 0)),L}(g).browserBufferSize||524288,v=g.browserBufferTimeout||1e3,x=!g.objectMode,A=function(I,L){const k=L.protocolId==="MQIsdp"&&L.protocolVersion===3?"mqttv3.1":"mqtt",V=f(L,I),H=new WebSocket(V,[k]);return H.binaryType="arraybuffer",H}(m,g),b=function(I,L,k){const V=new u({objectModeMode:I.objectMode});return V._write=L,V._flush=k,V}(g,function I(L,k,V){A.bufferedAmount>y&&setTimeout(I,v,L,k,V),x&&typeof L=="string"&&(L=a.from(L,"utf8"));try{A.send(L)}catch(H){return V(H)}V()},function(I){A.close(),I()});g.objectMode||(b._writev=R),b.on("close",()=>{A.close()});const C=A.addEventListener!==void 0;function T(){_.setReadable(b),_.setWritable(b),_.emit("connect")}function w(){_.end(),_.destroy()}function P(I){_.destroy(I)}function M(I){let L=I.data;L=L instanceof ArrayBuffer?a.from(L):a.from(L,"utf8"),b.push(L)}function R(I,L){const k=new Array(I.length);for(let V=0;V{x.destroy()}),x}}).call(this)}).call(this,t("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(t,i,r){const{Buffer:n}=t("buffer"),a=t("readable-stream").Transform,o=t("duplexify");let l,c,u;i.exports=function(h,d){if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");const f=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";(function(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})})(d);const p=function(g,_){const y=g.protocol==="wxs"?"wss":"ws";let v=y+"://"+g.hostname+g.path;return g.port&&g.port!==80&&g.port!==443&&(v=y+"://"+g.hostname+":"+g.port+g.path),typeof g.transformWsUrl=="function"&&(v=g.transformWsUrl(v,g,_)),v}(d,h);l=wx.connectSocket({url:p,protocols:[f]}),c=function(){const g=new a;return g._write=function(_,y,v){l.send({data:_.buffer,success:function(){v()},fail:function(x){v(new Error(x))}})},g._flush=function(_){l.close({success:function(){_()}})},g}(),(u=o.obj())._destroy=function(g,_){l.close({success:function(){_&&_(g)}})};const m=u.destroy;return u.destroy=(function(){u.destroy=m;const g=this;setTimeout(function(){l.close({fail:function(){g._destroy(new Error)}})},0)}).bind(u),l.onOpen(function(){u.setReadable(c),u.setWritable(c),u.emit("connect")}),l.onMessage(function(g){let _=g.data;_=_ instanceof ArrayBuffer?n.from(_):n.from(_,"utf8"),c.push(_)}),l.onClose(function(){u.end(),u.destroy()}),l.onError(function(g){u.destroy(new Error(g.errMsg))}),u}},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(t,i,r){function n(){if(!(this instanceof n))return new n;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}n.prototype.allocate=function(){const a=this.nextId++;return this.nextId===65536&&(this.nextId=1),a},n.prototype.getLastAllocated=function(){return this.nextId===1?65535:this.nextId-1},n.prototype.register=function(a){return!0},n.prototype.deallocate=function(a){},n.prototype.clear=function(){},i.exports=n},{}],8:[function(t,i,r){const n=t("xtend"),a=t("readable-stream").Readable,o={objectMode:!0},l={clean:!0};function c(u){if(!(this instanceof c))return new c(u);this.options=u||{},this.options=n(l,u),this._inflights=new Map}c.prototype.put=function(u,h){return this._inflights.set(u.messageId,u),h&&h(),this},c.prototype.createStream=function(){const u=new a(o),h=[];let d=!1,f=0;return this._inflights.forEach(function(p,m){h.push(p)}),u._read=function(){!d&&fthis.max)&&(this.aliasToTopic[o]=a,this.length=Object.keys(this.aliasToTopic).length,!0)},n.prototype.getTopicByAlias=function(a){return this.aliasToTopic[a]},n.prototype.clear=function(){this.aliasToTopic={}},i.exports=n},{}],10:[function(t,i,r){const n=t("lru-cache"),a=t("number-allocator").NumberAllocator;function o(l){if(!(this instanceof o))return new o(l);l>0&&(this.aliasToTopic=new n({max:l}),this.topicToAlias={},this.numberAllocator=new a(1,l),this.max=l,this.length=0)}o.prototype.put=function(l,c){if(c===0||c>this.max)return!1;const u=this.aliasToTopic.get(c);return u&&delete this.topicToAlias[u],this.aliasToTopic.set(c,l),this.topicToAlias[l]=c,this.numberAllocator.use(c),this.length=this.aliasToTopic.length,!0},o.prototype.getTopicByAlias=function(l){return this.aliasToTopic.get(l)},o.prototype.getAliasByTopic=function(l){const c=this.topicToAlias[l];return c!==void 0&&this.aliasToTopic.get(c),c},o.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},o.prototype.getLruAlias=function(){return this.numberAllocator.firstVacant()||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},i.exports=o},{"lru-cache":37,"number-allocator":46}],11:[function(t,i,r){function n(a){const o=a.split("/");for(let l=0;l0?_-4:_;for(m=0;m>16&255,v[x++]=p>>8&255,v[x++]=255&p;return y===2&&(p=a[f.charCodeAt(m)]<<2|a[f.charCodeAt(m+1)]>>4,v[x++]=255&p),y===1&&(p=a[f.charCodeAt(m)]<<10|a[f.charCodeAt(m+1)]<<4|a[f.charCodeAt(m+2)]>>2,v[x++]=p>>8&255,v[x++]=255&p),v},r.fromByteArray=function(f){for(var p,m=f.length,g=m%3,_=[],y=0,v=m-g;yv?v:y+16383));return g===1?(p=f[m-1],_.push(n[p>>2]+n[p<<4&63]+"==")):g===2&&(p=(f[m-2]<<8)+f[m-1],_.push(n[p>>10]+n[p>>4&63]+n[p<<2&63]+"=")),_.join("")};for(var n=[],a=[],o=typeof Uint8Array<"u"?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,u=l.length;c0)throw new Error("Invalid string. Length must be a multiple of 4");var m=f.indexOf("=");return m===-1&&(m=p),[m,m===p?0:4-m%4]}function d(f,p,m){for(var g,_,y=[],v=p;v>18&63]+n[_>>12&63]+n[_>>6&63]+n[63&_]);return y.join("")}a[45]=62,a[95]=63},{}],14:[function(t,i,r){const{Buffer:n}=t("buffer"),a=Symbol.for("BufferList");function o(l){if(!(this instanceof o))return new o(l);o._init.call(this,l)}o._init=function(l){Object.defineProperty(this,a,{value:!0}),this._bufs=[],this.length=0,l&&this.append(l)},o.prototype._new=function(l){return new o(l)},o.prototype._offset=function(l){if(l===0)return[0,0];let c=0;for(let u=0;uthis.length||l<0)return;const c=this._offset(l);return this._bufs[c[0]][c[1]]},o.prototype.slice=function(l,c){return typeof l=="number"&&l<0&&(l+=this.length),typeof c=="number"&&c<0&&(c+=this.length),this.copy(null,0,l,c)},o.prototype.copy=function(l,c,u,h){if((typeof u!="number"||u<0)&&(u=0),(typeof h!="number"||h>this.length)&&(h=this.length),u>=this.length||h<=0)return l||n.alloc(0);const d=!!l,f=this._offset(u),p=h-u;let m=p,g=d&&c||0,_=f[1];if(u===0&&h===this.length){if(!d)return this._bufs.length===1?this._bufs[0]:n.concat(this._bufs,this.length);for(let y=0;yv)){this._bufs[y].copy(l,g,_,_+m),g+=v;break}this._bufs[y].copy(l,g,_),g+=v,m-=v,_&&(_=0)}return l.length>g?l.slice(0,g):l},o.prototype.shallowSlice=function(l,c){if(l=l||0,c=typeof c!="number"?this.length:c,l<0&&(l+=this.length),c<0&&(c+=this.length),l===c)return this._new();const u=this._offset(l),h=this._offset(c),d=this._bufs.slice(u[0],h[0]+1);return h[1]===0?d.pop():d[d.length-1]=d[d.length-1].slice(0,h[1]),u[1]!==0&&(d[0]=d[0].slice(u[1])),this._new(d)},o.prototype.toString=function(l,c,u){return this.slice(c,u).toString(l)},o.prototype.consume=function(l){if(l=Math.trunc(l),Number.isNaN(l)||l<=0)return this;for(;this._bufs.length;){if(!(l>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(l),this.length-=l;break}l-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},o.prototype.duplicate=function(){const l=this._new();for(let c=0;cthis.length?this.length:c;const h=this._offset(c);let d=h[0],f=h[1];for(;d=l.length){const m=p.indexOf(l,f);if(m!==-1)return this._reverseOffset([d,m]);f=p.length-l.length+1}else{const m=this._reverseOffset([d,f]);if(this._match(m,l))return m;f++}f=0}return-1},o.prototype._match=function(l,c){if(this.length-ll)throw new RangeError('The value "'+N+'" is invalid for option "size"');var B=new Uint8Array(N);return B.__proto__=u.prototype,B}function u(N,B,Y){if(typeof N=="number"){if(typeof B=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(N)}return h(N,B,Y)}function h(N,B,Y){if(typeof N=="string")return function(ne,pe){if(typeof pe=="string"&&pe!==""||(pe="utf8"),!u.isEncoding(pe))throw new TypeError("Unknown encoding: "+pe);var ye=0|g(ne,pe),Ie=c(ye),Ne=Ie.write(ne,pe);return Ne!==ye&&(Ie=Ie.slice(0,Ne)),Ie}(N,B);if(ArrayBuffer.isView(N))return p(N);if(N==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof N);if(ue(N,ArrayBuffer)||N&&ue(N.buffer,ArrayBuffer))return function(ne,pe,ye){if(pe<0||ne.byteLength=l)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+l.toString(16)+" bytes");return 0|N}function g(N,B){if(u.isBuffer(N))return N.length;if(ArrayBuffer.isView(N)||ue(N,ArrayBuffer))return N.byteLength;if(typeof N!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof N);var Y=N.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&Y===0)return 0;for(var oe=!1;;)switch(B){case"ascii":case"latin1":case"binary":return Y;case"utf8":case"utf-8":return q(N).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*Y;case"hex":return Y>>>1;case"base64":return ie(N).length;default:if(oe)return te?-1:q(N).length;B=(""+B).toLowerCase(),oe=!0}}function _(N,B,Y){var te=N[B];N[B]=N[Y],N[Y]=te}function y(N,B,Y,te,oe){if(N.length===0)return-1;if(typeof Y=="string"?(te=Y,Y=0):Y>2147483647?Y=2147483647:Y<-2147483648&&(Y=-2147483648),ce(Y=+Y)&&(Y=oe?0:N.length-1),Y<0&&(Y=N.length+Y),Y>=N.length){if(oe)return-1;Y=N.length-1}else if(Y<0){if(!oe)return-1;Y=0}if(typeof B=="string"&&(B=u.from(B,te)),u.isBuffer(B))return B.length===0?-1:v(N,B,Y,te,oe);if(typeof B=="number")return B&=255,typeof Uint8Array.prototype.indexOf=="function"?oe?Uint8Array.prototype.indexOf.call(N,B,Y):Uint8Array.prototype.lastIndexOf.call(N,B,Y):v(N,[B],Y,te,oe);throw new TypeError("val must be string, number or Buffer")}function v(N,B,Y,te,oe){var ne,pe=1,ye=N.length,Ie=B.length;if(te!==void 0&&((te=String(te).toLowerCase())==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(N.length<2||B.length<2)return-1;pe=2,ye/=2,Ie/=2,Y/=2}function Ne(Et,ft){return pe===1?Et[ft]:Et.readUInt16BE(ft*pe)}if(oe){var Ve=-1;for(ne=Y;neye&&(Y=ye-Ie),ne=Y;ne>=0;ne--){for(var nt=!0,Ke=0;Keoe&&(te=oe):te=oe;var ne=B.length;te>ne/2&&(te=ne/2);for(var pe=0;pe>8,Ie=pe%256,Ne.push(Ie),Ne.push(ye);return Ne}(B,N.length-Y),N,Y,te)}function P(N,B,Y){return B===0&&Y===N.length?a.fromByteArray(N):a.fromByteArray(N.slice(B,Y))}function M(N,B,Y){Y=Math.min(N.length,Y);for(var te=[],oe=B;oe239?4:Ne>223?3:Ne>191?2:1;if(oe+nt<=Y)switch(nt){case 1:Ne<128&&(Ve=Ne);break;case 2:(192&(ne=N[oe+1]))==128&&(Ie=(31&Ne)<<6|63&ne)>127&&(Ve=Ie);break;case 3:ne=N[oe+1],pe=N[oe+2],(192&ne)==128&&(192&pe)==128&&(Ie=(15&Ne)<<12|(63&ne)<<6|63&pe)>2047&&(Ie<55296||Ie>57343)&&(Ve=Ie);break;case 4:ne=N[oe+1],pe=N[oe+2],ye=N[oe+3],(192&ne)==128&&(192&pe)==128&&(192&ye)==128&&(Ie=(15&Ne)<<18|(63&ne)<<12|(63&pe)<<6|63&ye)>65535&&Ie<1114112&&(Ve=Ie)}Ve===null?(Ve=65533,nt=1):Ve>65535&&(Ve-=65536,te.push(Ve>>>10&1023|55296),Ve=56320|1023&Ve),te.push(Ve),oe+=nt}return function(Ke){var Et=Ke.length;if(Et<=R)return String.fromCharCode.apply(String,Ke);for(var ft="",Tt=0;Tt"u"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),typeof Symbol<"u"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(N,B,Y){return h(N,B,Y)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(N,B,Y){return function(te,oe,ne){return d(te),te<=0?c(te):oe!==void 0?typeof ne=="string"?c(te).fill(oe,ne):c(te).fill(oe):c(te)}(N,B,Y)},u.allocUnsafe=function(N){return f(N)},u.allocUnsafeSlow=function(N){return f(N)},u.isBuffer=function(N){return N!=null&&N._isBuffer===!0&&N!==u.prototype},u.compare=function(N,B){if(ue(N,Uint8Array)&&(N=u.from(N,N.offset,N.byteLength)),ue(B,Uint8Array)&&(B=u.from(B,B.offset,B.byteLength)),!u.isBuffer(N)||!u.isBuffer(B))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(N===B)return 0;for(var Y=N.length,te=B.length,oe=0,ne=Math.min(Y,te);oethis.length||((te===void 0||te>this.length)&&(te=this.length),te<=0)||(te>>>=0)<=(Y>>>=0))return"";for(B||(B="utf8");;)switch(B){case"hex":return k(this,Y,te);case"utf8":case"utf-8":return M(this,Y,te);case"ascii":return I(this,Y,te);case"latin1":case"binary":return L(this,Y,te);case"base64":return P(this,Y,te);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,Y,te);default:if(oe)throw new TypeError("Unknown encoding: "+B);B=(B+"").toLowerCase(),oe=!0}}).apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(N){if(!u.isBuffer(N))throw new TypeError("Argument must be a Buffer");return this===N||u.compare(this,N)===0},u.prototype.inspect=function(){var N="",B=r.INSPECT_MAX_BYTES;return N=this.toString("hex",0,B).replace(/(.{2})/g,"$1 ").trim(),this.length>B&&(N+=" ... "),""},u.prototype.compare=function(N,B,Y,te,oe){if(ue(N,Uint8Array)&&(N=u.from(N,N.offset,N.byteLength)),!u.isBuffer(N))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof N);if(B===void 0&&(B=0),Y===void 0&&(Y=N?N.length:0),te===void 0&&(te=0),oe===void 0&&(oe=this.length),B<0||Y>N.length||te<0||oe>this.length)throw new RangeError("out of range index");if(te>=oe&&B>=Y)return 0;if(te>=oe)return-1;if(B>=Y)return 1;if(B>>>=0,Y>>>=0,te>>>=0,oe>>>=0,this===N)return 0;for(var ne=oe-te,pe=Y-B,ye=Math.min(ne,pe),Ie=this.slice(te,oe),Ne=N.slice(B,Y),Ve=0;Ve>>=0,isFinite(Y)?(Y>>>=0,te===void 0&&(te="utf8")):(te=Y,Y=void 0)}var oe=this.length-B;if((Y===void 0||Y>oe)&&(Y=oe),N.length>0&&(Y<0||B<0)||B>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");for(var ne=!1;;)switch(te){case"hex":return x(this,N,B,Y);case"utf8":case"utf-8":return A(this,N,B,Y);case"ascii":return b(this,N,B,Y);case"latin1":case"binary":return C(this,N,B,Y);case"base64":return T(this,N,B,Y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,N,B,Y);default:if(ne)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ne=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;function I(N,B,Y){var te="";Y=Math.min(N.length,Y);for(var oe=B;oete)&&(Y=te);for(var oe="",ne=B;neY)throw new RangeError("Trying to access beyond buffer length")}function j(N,B,Y,te,oe,ne){if(!u.isBuffer(N))throw new TypeError('"buffer" argument must be a Buffer instance');if(B>oe||BN.length)throw new RangeError("Index out of range")}function z(N,B,Y,te,oe,ne){if(Y+te>N.length)throw new RangeError("Index out of range");if(Y<0)throw new RangeError("Index out of range")}function K(N,B,Y,te,oe){return B=+B,Y>>>=0,oe||z(N,0,Y,4),o.write(N,B,Y,te,23,4),Y+4}function U(N,B,Y,te,oe){return B=+B,Y>>>=0,oe||z(N,0,Y,8),o.write(N,B,Y,te,52,8),Y+8}u.prototype.slice=function(N,B){var Y=this.length;N=~~N,B=B===void 0?Y:~~B,N<0?(N+=Y)<0&&(N=0):N>Y&&(N=Y),B<0?(B+=Y)<0&&(B=0):B>Y&&(B=Y),B>>=0,B>>>=0,Y||H(N,B,this.length);for(var te=this[N],oe=1,ne=0;++ne>>=0,B>>>=0,Y||H(N,B,this.length);for(var te=this[N+--B],oe=1;B>0&&(oe*=256);)te+=this[N+--B]*oe;return te},u.prototype.readUInt8=function(N,B){return N>>>=0,B||H(N,1,this.length),this[N]},u.prototype.readUInt16LE=function(N,B){return N>>>=0,B||H(N,2,this.length),this[N]|this[N+1]<<8},u.prototype.readUInt16BE=function(N,B){return N>>>=0,B||H(N,2,this.length),this[N]<<8|this[N+1]},u.prototype.readUInt32LE=function(N,B){return N>>>=0,B||H(N,4,this.length),(this[N]|this[N+1]<<8|this[N+2]<<16)+16777216*this[N+3]},u.prototype.readUInt32BE=function(N,B){return N>>>=0,B||H(N,4,this.length),16777216*this[N]+(this[N+1]<<16|this[N+2]<<8|this[N+3])},u.prototype.readIntLE=function(N,B,Y){N>>>=0,B>>>=0,Y||H(N,B,this.length);for(var te=this[N],oe=1,ne=0;++ne=(oe*=128)&&(te-=Math.pow(2,8*B)),te},u.prototype.readIntBE=function(N,B,Y){N>>>=0,B>>>=0,Y||H(N,B,this.length);for(var te=B,oe=1,ne=this[N+--te];te>0&&(oe*=256);)ne+=this[N+--te]*oe;return ne>=(oe*=128)&&(ne-=Math.pow(2,8*B)),ne},u.prototype.readInt8=function(N,B){return N>>>=0,B||H(N,1,this.length),128&this[N]?-1*(255-this[N]+1):this[N]},u.prototype.readInt16LE=function(N,B){N>>>=0,B||H(N,2,this.length);var Y=this[N]|this[N+1]<<8;return 32768&Y?4294901760|Y:Y},u.prototype.readInt16BE=function(N,B){N>>>=0,B||H(N,2,this.length);var Y=this[N+1]|this[N]<<8;return 32768&Y?4294901760|Y:Y},u.prototype.readInt32LE=function(N,B){return N>>>=0,B||H(N,4,this.length),this[N]|this[N+1]<<8|this[N+2]<<16|this[N+3]<<24},u.prototype.readInt32BE=function(N,B){return N>>>=0,B||H(N,4,this.length),this[N]<<24|this[N+1]<<16|this[N+2]<<8|this[N+3]},u.prototype.readFloatLE=function(N,B){return N>>>=0,B||H(N,4,this.length),o.read(this,N,!0,23,4)},u.prototype.readFloatBE=function(N,B){return N>>>=0,B||H(N,4,this.length),o.read(this,N,!1,23,4)},u.prototype.readDoubleLE=function(N,B){return N>>>=0,B||H(N,8,this.length),o.read(this,N,!0,52,8)},u.prototype.readDoubleBE=function(N,B){return N>>>=0,B||H(N,8,this.length),o.read(this,N,!1,52,8)},u.prototype.writeUIntLE=function(N,B,Y,te){N=+N,B>>>=0,Y>>>=0,te||j(this,N,B,Y,Math.pow(2,8*Y)-1,0);var oe=1,ne=0;for(this[B]=255&N;++ne>>=0,Y>>>=0,te||j(this,N,B,Y,Math.pow(2,8*Y)-1,0);var oe=Y-1,ne=1;for(this[B+oe]=255&N;--oe>=0&&(ne*=256);)this[B+oe]=N/ne&255;return B+Y},u.prototype.writeUInt8=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,1,255,0),this[B]=255&N,B+1},u.prototype.writeUInt16LE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,2,65535,0),this[B]=255&N,this[B+1]=N>>>8,B+2},u.prototype.writeUInt16BE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,2,65535,0),this[B]=N>>>8,this[B+1]=255&N,B+2},u.prototype.writeUInt32LE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,4,4294967295,0),this[B+3]=N>>>24,this[B+2]=N>>>16,this[B+1]=N>>>8,this[B]=255&N,B+4},u.prototype.writeUInt32BE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,4,4294967295,0),this[B]=N>>>24,this[B+1]=N>>>16,this[B+2]=N>>>8,this[B+3]=255&N,B+4},u.prototype.writeIntLE=function(N,B,Y,te){if(N=+N,B>>>=0,!te){var oe=Math.pow(2,8*Y-1);j(this,N,B,Y,oe-1,-oe)}var ne=0,pe=1,ye=0;for(this[B]=255&N;++ne>0)-ye&255;return B+Y},u.prototype.writeIntBE=function(N,B,Y,te){if(N=+N,B>>>=0,!te){var oe=Math.pow(2,8*Y-1);j(this,N,B,Y,oe-1,-oe)}var ne=Y-1,pe=1,ye=0;for(this[B+ne]=255&N;--ne>=0&&(pe*=256);)N<0&&ye===0&&this[B+ne+1]!==0&&(ye=1),this[B+ne]=(N/pe>>0)-ye&255;return B+Y},u.prototype.writeInt8=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,1,127,-128),N<0&&(N=255+N+1),this[B]=255&N,B+1},u.prototype.writeInt16LE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,2,32767,-32768),this[B]=255&N,this[B+1]=N>>>8,B+2},u.prototype.writeInt16BE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,2,32767,-32768),this[B]=N>>>8,this[B+1]=255&N,B+2},u.prototype.writeInt32LE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,4,2147483647,-2147483648),this[B]=255&N,this[B+1]=N>>>8,this[B+2]=N>>>16,this[B+3]=N>>>24,B+4},u.prototype.writeInt32BE=function(N,B,Y){return N=+N,B>>>=0,Y||j(this,N,B,4,2147483647,-2147483648),N<0&&(N=4294967295+N+1),this[B]=N>>>24,this[B+1]=N>>>16,this[B+2]=N>>>8,this[B+3]=255&N,B+4},u.prototype.writeFloatLE=function(N,B,Y){return K(this,N,B,!0,Y)},u.prototype.writeFloatBE=function(N,B,Y){return K(this,N,B,!1,Y)},u.prototype.writeDoubleLE=function(N,B,Y){return U(this,N,B,!0,Y)},u.prototype.writeDoubleBE=function(N,B,Y){return U(this,N,B,!1,Y)},u.prototype.copy=function(N,B,Y,te){if(!u.isBuffer(N))throw new TypeError("argument should be a Buffer");if(Y||(Y=0),te||te===0||(te=this.length),B>=N.length&&(B=N.length),B||(B=0),te>0&&te=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),N.length-B=0;--ne)N[ne+B]=this[ne+Y];else Uint8Array.prototype.set.call(N,this.subarray(Y,te),B);return oe},u.prototype.fill=function(N,B,Y,te){if(typeof N=="string"){if(typeof B=="string"?(te=B,B=0,Y=this.length):typeof Y=="string"&&(te=Y,Y=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!u.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(N.length===1){var oe=N.charCodeAt(0);(te==="utf8"&&oe<128||te==="latin1")&&(N=oe)}}else typeof N=="number"&&(N&=255);if(B<0||this.length>>=0,Y=Y===void 0?this.length:Y>>>0,N||(N=0),typeof N=="number")for(ne=B;ne55295&&Y<57344){if(!oe){if(Y>56319){(B-=3)>-1&&ne.push(239,191,189);continue}if(pe+1===te){(B-=3)>-1&&ne.push(239,191,189);continue}oe=Y;continue}if(Y<56320){(B-=3)>-1&&ne.push(239,191,189),oe=Y;continue}Y=65536+(oe-55296<<10|Y-56320)}else oe&&(B-=3)>-1&&ne.push(239,191,189);if(oe=null,Y<128){if((B-=1)<0)break;ne.push(Y)}else if(Y<2048){if((B-=2)<0)break;ne.push(Y>>6|192,63&Y|128)}else if(Y<65536){if((B-=3)<0)break;ne.push(Y>>12|224,Y>>6&63|128,63&Y|128)}else{if(!(Y<1114112))throw new Error("Invalid code point");if((B-=4)<0)break;ne.push(Y>>18|240,Y>>12&63|128,Y>>6&63|128,63&Y|128)}}return ne}function ie(N){return a.toByteArray(function(B){if((B=(B=B.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;B.length%4!=0;)B+="=";return B}(N))}function ae(N,B,Y,te){for(var oe=0;oe=B.length||oe>=N.length);++oe)B[oe+Y]=N[oe];return oe}function ue(N,B){return N instanceof B||N!=null&&N.constructor!=null&&N.constructor.name!=null&&N.constructor.name===B.name}function ce(N){return N!=N}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(t,i,r){(function(n){(function(){r.formatArgs=function(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+i.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;o.splice(1,0,l,"color: inherit");let c=0,u=0;o[0].replace(/%[a-zA-Z%]/g,h=>{h!=="%%"&&h==="%c"&&(u=++c)}),o.splice(u,0,l)},r.save=function(o){try{o?r.storage.setItem("debug",o):r.storage.removeItem("debug")}catch{}},r.load=function(){let o;try{o=r.storage.getItem("debug")}catch{}return!o&&n!==void 0&&"env"in n&&(o=n.env.DEBUG),o},r.useColors=function(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},r.storage=function(){try{return localStorage}catch{}}(),r.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),r.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],r.log=console.debug||console.log||(()=>{}),i.exports=t("./common")(r);const{formatters:a}=i.exports;a.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}).call(this)}).call(this,t("_process"))},{"./common":19,_process:50}],19:[function(t,i,r){i.exports=function(n){function a(c){let u,h,d,f=null;function p(...m){if(!p.enabled)return;const g=p,_=Number(new Date),y=_-(u||_);g.diff=y,g.prev=u,g.curr=_,u=_,m[0]=a.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let v=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(x,A)=>{if(x==="%%")return"%";v++;const b=a.formatters[A];if(typeof b=="function"){const C=m[v];x=b.call(g,C),m.splice(v,1),v--}return x}),a.formatArgs.call(g,m),(g.log||a.log).apply(g,m)}return p.namespace=c,p.useColors=a.useColors(),p.color=a.selectColor(c),p.extend=o,p.destroy=a.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==a.namespaces&&(h=a.namespaces,d=a.enabled(c)),d),set:m=>{f=m}}),typeof a.init=="function"&&a.init(p),p}function o(c,u){const h=a(this.namespace+(u===void 0?":":u)+c);return h.log=this.log,h}function l(c){return c.toString().substring(2,c.toString().length-2).replace(/\.\*\?$/,"*")}return a.debug=a,a.default=a,a.coerce=function(c){return c instanceof Error?c.stack||c.message:c},a.disable=function(){const c=[...a.names.map(l),...a.skips.map(l).map(u=>"-"+u)].join(",");return a.enable(""),c},a.enable=function(c){let u;a.save(c),a.namespaces=c,a.names=[],a.skips=[];const h=(typeof c=="string"?c:"").split(/[\s,]+/),d=h.length;for(u=0;u{a[c]=n[c]}),a.names=[],a.skips=[],a.formatters={},a.selectColor=function(c){let u=0;for(let h=0;h0&&w.length>C){w.warned=!0;var P=new Error("Possible EventEmitter memory leak detected. "+w.length+' "'+String(x)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');P.name="MaxListenersExceededWarning",P.emitter=v,P.type=x,P.count=w.length,typeof console=="object"&&console.warn&&console.warn("%s: %s",P.name,P.message)}}else w=T[x]=A,++v._eventsCount;return v}function p(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var v=new Array(arguments.length),x=0;x1&&(x=arguments[1]),x instanceof Error)throw x;var M=new Error('Unhandled "error" event. ('+x+")");throw M.context=x,M}if(!(A=w[v]))return!1;var R=typeof A=="function";switch(b=arguments.length){case 1:(function(I,L,k){if(L)I.call(k);else for(var V=I.length,H=y(I,V),j=0;j=0;T--)if(A[T]===x||A[T].listener===x){w=A[T].listener,C=T;break}if(C<0)return this;C===0?A.shift():function(P,M){for(var R=M,I=R+1,L=P.length;I=0;b--)this.removeListener(v,x[b]);return this},l.prototype.listeners=function(v){return g(this,v,!0)},l.prototype.rawListeners=function(v){return g(this,v,!1)},l.listenerCount=function(v,x){return typeof v.listenerCount=="function"?v.listenerCount(x):_.call(v,x)},l.prototype.listenerCount=_,l.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(t,i,r){r.read=function(n,a,o,l,c){var u,h,d=8*c-l-1,f=(1<>1,m=-7,g=o?c-1:0,_=o?-1:1,y=n[a+g];for(g+=_,u=y&(1<<-m)-1,y>>=-m,m+=d;m>0;u=256*u+n[a+g],g+=_,m-=8);for(h=u&(1<<-m)-1,u>>=-m,m+=l;m>0;h=256*h+n[a+g],g+=_,m-=8);if(u===0)u=1-p;else{if(u===f)return h?NaN:1/0*(y?-1:1);h+=Math.pow(2,l),u-=p}return(y?-1:1)*h*Math.pow(2,u-l)},r.write=function(n,a,o,l,c,u){var h,d,f,p=8*u-c-1,m=(1<>1,_=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=l?0:u-1,v=l?1:-1,x=a<0||a===0&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(d=isNaN(a)?1:0,h=m):(h=Math.floor(Math.log(a)/Math.LN2),a*(f=Math.pow(2,-h))<1&&(h--,f*=2),(a+=h+g>=1?_/f:_*Math.pow(2,1-g))*f>=2&&(h++,f/=2),h+g>=m?(d=0,h=m):h+g>=1?(d=(a*f-1)*Math.pow(2,c),h+=g):(d=a*Math.pow(2,g-1)*Math.pow(2,c),h=0));c>=8;n[o+y]=255&d,y+=v,d/=256,c-=8);for(h=h<0;n[o+y]=255&h,y+=v,h/=256,p-=8);n[o+y-v]|=128*x}},{}],24:[function(t,i,r){typeof Object.create=="function"?i.exports=function(n,a){a&&(n.super_=a,n.prototype=Object.create(a.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}))}:i.exports=function(n,a){if(a){n.super_=a;var o=function(){};o.prototype=a.prototype,n.prototype=new o,n.prototype.constructor=n}}},{}],25:[function(t,i,r){Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function a(o,l){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=o,this.value=l}return a.prototype.rotateLeft=function(){var o=this.parent,l=this.brother,c=this.leftChild,u=this.rightChild;if(!u)throw new Error("unknown error");var h=u.leftChild,d=u.rightChild;return o&&(o.leftChild===this?o.leftChild=u:o.rightChild===this&&(o.rightChild=u)),u.parent=o,u.brother=l,u.leftChild=this,u.rightChild=d,l&&(l.brother=u),this.parent=u,this.brother=d,this.leftChild=c,this.rightChild=h,d&&(d.parent=u,d.brother=this),c&&(c.parent=this,c.brother=h),h&&(h.parent=this,h.brother=c),u},a.prototype.rotateRight=function(){var o=this.parent,l=this.brother,c=this.leftChild;if(!c)throw new Error("unknown error");var u=this.rightChild,h=c.leftChild,d=c.rightChild;return o&&(o.leftChild===this?o.leftChild=c:o.rightChild===this&&(o.rightChild=c)),c.parent=o,c.brother=l,c.leftChild=h,c.rightChild=this,l&&(l.brother=c),h&&(h.parent=c,h.brother=this),this.parent=c,this.brother=h,this.leftChild=d,this.rightChild=u,d&&(d.parent=this,d.brother=u),u&&(u.parent=this,u.brother=d),c},a.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},a.TreeNodeColorType={red:!0,black:!1},a}();Object.freeze(n),r.default=n},{}],26:[function(t,i,r){var n=this&&this.__generator||function(o,l){var c,u,h,d,f={label:0,sent:function(){if(1&h[0])throw h[1];return h[1]},trys:[],ops:[]};return d={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(d[Symbol.iterator]=function(){return this}),d;function p(m){return function(g){return function(_){if(c)throw new TypeError("Generator is already executing.");for(;f;)try{if(c=1,u&&(h=2&_[0]?u.return:_[0]?u.throw||((h=u.return)&&h.call(u),0):u.next)&&!(h=h.call(u,_[1])).done)return h;switch(u=0,h&&(_=[2&_[0],h.value]),_[0]){case 0:case 1:h=_;break;case 4:return f.label++,{value:_[1],done:!1};case 5:f.label++,u=_[1],_=[0];continue;case 7:_=f.ops.pop(),f.trys.pop();continue;default:if(!(h=(h=f.trys).length>0&&h[h.length-1])&&(_[0]===6||_[0]===2)){f=0;continue}if(_[0]===3&&(!h||_[1]>h[0]&&_[1]A)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(x/a.bucketSize),curNodePointerIndex:x%a.bucketSize}};this.getElementByPos=function(y){var v=g(y),x=v.curNodeBucketIndex,A=v.curNodePointerIndex;return c[x][A]},this.eraseElementByPos=function(y){var v=this;if(y<0||y>m)throw new Error("pos should more than 0 and less than queue's size");if(y===0)this.popFront();else if(y===this.size())this.popBack();else{for(var x=[],A=y+1;A0?--f:u0&&--m)},this.setElementByPos=function(y,v){var x=g(y),A=x.curNodeBucketIndex,b=x.curNodePointerIndex;c[A][b]=v},this.insert=function(y,v,x){var A=this;if(x===void 0&&(x=1),y===0)for(;x--;)this.pushFront(v);else if(y===this.size())for(;x--;)this.pushBack(v);else{for(var b=[],C=y;C0?--h:u>0&&(--u,h=a.bucketSize-1)),++m,c[u][h]=y},this.popFront=function(){this.empty()||(this.size()!==1&&(h0&&--m)},this.shrinkToFit=function(){var y=this,v=[];this.forEach(function(C){v.push(C)});var x=v.length;c=[];for(var A=Math.ceil(x/a.bucketSize),b=0;b0&&p[p.length-1])&&(x[0]===6||x[0]===2)){g=0;continue}if(x[0]===3&&(!p||x[1]>p[0]&&x[1]=u.length&&(u=void 0),{value:u&&u[f++],done:!u}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../LinkList/LinkList"),l=t("../Map/Map");function c(u,h,d){var f=this;if(u===void 0&&(u=[]),h===void 0&&(h=c.initSize),d=d||function(_){var y,v,x=0,A="";if(typeof _=="number")x=((x=Math.floor(_))<<5)-x,x&=x;else{A=typeof _!="string"?JSON.stringify(_):_;try{for(var b=a(A),C=b.next();!C.done;C=b.next())x=(x<<5)-x+C.value.charCodeAt(0),x&=x}catch(T){y={error:T}}finally{try{C&&!C.done&&(v=b.return)&&v.call(b)}finally{if(y)throw y.error}}}return x^=x>>>16},(h&h-1)!=0)throw new Error("initBucketNum must be 2 to the power of n");var p=0,m=[],g=Math.max(c.initSize,Math.min(c.maxSize,h));this.size=function(){return p},this.empty=function(){return p===0},this.clear=function(){p=0,g=h,m=[]},this.forEach=function(_){var y=0;m.forEach(function(v){v.forEach(function(x){_(x,y++)})})},this.setElement=function(_,y){var v,x;if(_==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(y!=null){var A=d(_)&g-1;if(m[A]){var b=m[A].size();if(m[A]instanceof o.default){try{for(var C=a(m[A]),T=C.next();!T.done;T=C.next()){var w=T.value;if(w.key===_)return void(w.value=y)}}catch(M){v={error:M}}finally{try{T&&!T.done&&(x=C.return)&&x.call(C)}finally{if(v)throw v.error}}m[A].pushBack({key:_,value:y}),m[A].size()>=c.treeifyThreshold&&(m[A]=new l.default(m[A]))}else m[A].setElement(_,y);var P=m[A].size();p+=P-b}else++p,m[A]=new o.default([{key:_,value:y}]);p>g*c.sigma&&(function(M){if(!(M>=c.maxSize)){g=2*M;var R=[];m.forEach(function(I,L){if(!I.empty()){if(I instanceof o.default&&I.size()===1){var k=I.front(),V=k.key,H=k.value;R[d(V)&g-1]=new o.default([{key:V,value:H}])}else if(I instanceof l.default){var j=new o.default,z=new o.default;I.forEach(function(W){d(W.key)&M?z.pushBack(W):j.pushBack(W)}),j.size()>c.untreeifyThreshold?R[L]=new l.default(j):j.size()&&(R[L]=j),z.size()>c.untreeifyThreshold?R[L+M]=new l.default(z):z.size()&&(R[L+M]=z)}else{var K=new o.default,U=new o.default;I.forEach(function(W){d(W.key)&M?U.pushBack(W):K.pushBack(W)}),K.size()&&(R[L]=K),U.size()&&(R[L+M]=U)}m[L].clear()}}),m=R}}).call(this,g)}else this.eraseElementByKey(_)},this.getElementByKey=function(_){var y,v,x=d(_)&g-1;if(m[x]){if(m[x]instanceof l.default)return m[x].getElementByKey(_);try{for(var A=a(m[x]),b=A.next();!b.done;b=A.next()){var C=b.value;if(C.key===_)return C.value}}catch(T){y={error:T}}finally{try{b&&!b.done&&(v=A.return)&&v.call(A)}finally{if(y)throw y.error}}}},this.eraseElementByKey=function(_){var y,v,x=d(_)&g-1;if(m[x]){var A=m[x].size();if(m[x]instanceof l.default)m[x].eraseElementByKey(_),m[x].size()<=c.untreeifyThreshold&&(m[x]=new o.default(m[x]));else{var b=-1;try{for(var C=a(m[x]),T=C.next();!T.done;T=C.next())if(++b,T.value.key===_){m[x].eraseElementByPos(b);break}}catch(P){y={error:P}}finally{try{T&&!T.done&&(v=C.return)&&v.call(C)}finally{if(y)throw y.error}}}var w=m[x].size();p+=w-A}},this.find=function(_){var y,v,x=d(_)&g-1;if(!m[x])return!1;if(m[x]instanceof l.default)return m[x].find(_);try{for(var A=a(m[x]),b=A.next();!b.done;b=A.next())if(b.value.key===_)return!0}catch(C){y={error:C}}finally{try{b&&!b.done&&(v=A.return)&&v.call(A)}finally{if(y)throw y.error}}return!1},this[Symbol.iterator]=function(){return function(){var _,y,v,x,A,b;return n(this,function(C){switch(C.label){case 0:_=0,C.label=1;case 1:if(!(_=g)return[3,10];C.label=2;case 2:C.trys.push([2,7,8,9]),A=void 0,y=a(m[_]),v=y.next(),C.label=3;case 3:return v.done?[3,6]:[4,v.value];case 4:C.sent(),C.label=5;case 5:return v=y.next(),[3,3];case 6:return[3,9];case 7:return x=C.sent(),A={error:x},[3,9];case 8:try{v&&!v.done&&(b=y.return)&&b.call(y)}finally{if(A)throw A.error}return[7];case 9:return++_,[3,1];case 10:return[2]}})}()},u.forEach(function(_){var y=_.key,v=_.value;return f.setElement(y,v)}),Object.freeze(this)}c.initSize=16,c.maxSize=1<<30,c.sigma=.75,c.treeifyThreshold=8,c.untreeifyThreshold=6,c.minTreeifySize=64,Object.freeze(c),r.default=c},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(t,i,r){var n=this&&this.__generator||function(u,h){var d,f,p,m,g={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return m={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function _(y){return function(v){return function(x){if(d)throw new TypeError("Generator is already executing.");for(;g;)try{if(d=1,f&&(p=2&x[0]?f.return:x[0]?f.throw||((p=f.return)&&p.call(f),0):f.next)&&!(p=p.call(f,x[1])).done)return p;switch(f=0,p&&(x=[2&x[0],p.value]),x[0]){case 0:case 1:p=x;break;case 4:return g.label++,{value:x[1],done:!1};case 5:g.label++,f=x[1],x=[0];continue;case 7:x=g.ops.pop(),g.trys.pop();continue;default:if(!(p=(p=g.trys).length>0&&p[p.length-1])&&(x[0]===6||x[0]===2)){g=0;continue}if(x[0]===3&&(!p||x[1]>p[0]&&x[1]=u.length&&(u=void 0),{value:u&&u[f++],done:!u}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../Set/Set"),l=t("../LinkList/LinkList");function c(u,h,d){var f=this;if(u===void 0&&(u=[]),h===void 0&&(h=c.initSize),d=d||function(_){var y=0,v="";if(typeof _=="number")y=((y=Math.floor(_))<<5)-y,y&=y;else{v=typeof _!="string"?JSON.stringify(_):_;for(var x=0;x>>16},(h&h-1)!=0)throw new Error("initBucketNum must be 2 to the power of n");var p=0,m=[],g=Math.max(c.initSize,Math.min(c.maxSize,h));this.size=function(){return p},this.empty=function(){return p===0},this.clear=function(){p=0,g=h,m=[]},this.forEach=function(_){var y=0;m.forEach(function(v){v.forEach(function(x){_(x,y++)})})},this.insert=function(_){if(_==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var y=d(_)&g-1;if(m[y]){var v=m[y].size();if(m[y]instanceof l.default){if(m[y].find(_))return;m[y].pushBack(_),m[y].size()>=c.treeifyThreshold&&(m[y]=new o.default(m[y]))}else m[y].insert(_);var x=m[y].size();p+=x-v}else m[y]=new l.default([_]),++p;p>g*c.sigma&&(function(A){if(!(A>=c.maxSize)){g=2*A;var b=[];m.forEach(function(C,T){if(!C.empty()){if(C instanceof l.default&&C.size()===1){var w=C.front();if(w===void 0)throw new Error("unknown error");b[d(w)&g-1]=new l.default([w])}else if(C instanceof o.default){var P=new l.default,M=new l.default;C.forEach(function(L){d(L)&A?M.pushBack(L):P.pushBack(L)}),P.size()>c.untreeifyThreshold?b[T]=new o.default(P):P.size()&&(b[T]=P),M.size()>c.untreeifyThreshold?b[T+A]=new o.default(M):M.size()&&(b[T+A]=M)}else{var R=new l.default,I=new l.default;C.forEach(function(L){d(L)&A?I.pushBack(L):R.pushBack(L)}),R.size()&&(b[T]=R),I.size()&&(b[T+A]=I)}m[T].clear()}}),m=b}}).call(this,g)},this.eraseElementByValue=function(_){var y=d(_)&g-1;if(m[y]){var v=m[y].size();m[y].eraseElementByValue(_),m[y]instanceof o.default&&m[y].size()<=c.untreeifyThreshold&&(m[y]=new l.default(m[y]));var x=m[y].size();p+=x-v}},this.find=function(_){var y=d(_)&g-1;return!!m[y]&&m[y].find(_)},this[Symbol.iterator]=function(){return function(){var _,y,v,x,A,b;return n(this,function(C){switch(C.label){case 0:_=0,C.label=1;case 1:if(!(_=g)return[3,10];C.label=2;case 2:C.trys.push([2,7,8,9]),A=void 0,y=a(m[_]),v=y.next(),C.label=3;case 3:return v.done?[3,6]:[4,v.value];case 4:C.sent(),C.label=5;case 5:return v=y.next(),[3,3];case 6:return[3,9];case 7:return x=C.sent(),A={error:x},[3,9];case 8:try{v&&!v.done&&(b=y.return)&&b.call(y)}finally{if(A)throw A.error}return[7];case 9:return++_,[3,1];case 10:return[2]}})}()},u.forEach(function(_){return f.insert(_)}),Object.freeze(this)}c.initSize=16,c.maxSize=1<<30,c.sigma=.75,c.treeifyThreshold=8,c.untreeifyThreshold=6,c.minTreeifySize=64,Object.freeze(c),r.default=c},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(t,i,r){var n=this&&this.__generator||function(l,c){var u,h,d,f,p={label:0,sent:function(){if(1&d[0])throw d[1];return d[1]},trys:[],ops:[]};return f={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function m(g){return function(_){return function(y){if(u)throw new TypeError("Generator is already executing.");for(;p;)try{if(u=1,h&&(d=2&y[0]?h.return:y[0]?h.throw||((d=h.return)&&d.call(h),0):h.next)&&!(d=d.call(h,y[1])).done)return d;switch(h=0,d&&(y=[2&y[0],d.value]),y[0]){case 0:case 1:d=y;break;case 4:return p.label++,{value:y[1],done:!1};case 5:p.label++,h=y[1],y=[0];continue;case 7:y=p.ops.pop(),p.trys.pop();continue;default:if(!(d=(d=p.trys).length>0&&d[d.length-1])&&(y[0]===6||y[0]===2)){p=0;continue}if(y[0]===3&&(!d||y[1]>d[0]&&y[1]=u)throw new Error("pos must more then 0 and less then the list length");for(var p=h;f--&&p;)p=p.next;if(!p||p.value===void 0)throw new Error("unknown error");return p.value},this.eraseElementByPos=function(f){if(f<0||f>=u)throw new Error("erase pos must more then 0 and less then the list length");if(f===0)this.popFront();else if(f===u-1)this.popBack();else{for(var p=h;f--;){if(!(p!=null&&p.next))throw new Error("unknown error");p=p.next}if(!p||!p.pre||!p.next)throw new Error("unknown error");var m=p.pre,g=p.next;g.pre=m,m.next=g,u>0&&--u}},this.eraseElementByValue=function(f){for(;h&&h.value===f;)this.popFront();for(;d&&d.value===f;)this.popBack();if(h)for(var p=h;p;){if(p.value===f){var m=p.pre,g=p.next;g&&(g.pre=m),m&&(m.next=g),u>0&&--u}p=p.next}},this.pushBack=function(f){if(f==null)throw new Error("you can't push null or undefined here");++u;var p=new a(f);d?(d.next=p,p.pre=d,d=p):h=d=p},this.popBack=function(){d&&(u>0&&--u,d&&(h===d?h=d=void 0:(d=d.pre)&&(d.next=void 0)))},this.setElementByPos=function(f,p){if(p==null)throw new Error("you can't set null or undefined here");if(f<0||f>=u)throw new Error("pos must more then 0 and less then the list length");for(var m=h;f--;){if(!m)throw new Error("unknown error");m=m.next}m&&(m.value=p)},this.insert=function(f,p,m){if(m===void 0&&(m=1),p==null)throw new Error("you can't insert null or undefined here");if(f<0||f>u)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(m<0)throw new Error("insert size must more than 0");if(f===0)for(;m--;)this.pushFront(p);else if(f===u)for(;m--;)this.pushBack(p);else{for(var g=h,_=1;_0&&--u;f.next=p.next,f.next&&(f.next.pre=f),f=f.next}},this.sort=function(f){var p=[];this.forEach(function(g){p.push(g)}),p.sort(f);var m=h;p.forEach(function(g){m&&(m.value=g,m=m.next)})},this.pushFront=function(f){if(f==null)throw new Error("you can't push null or undefined here");++u;var p=new a(f);h?(p.next=h,h.pre=p,h=p):h=d=p},this.popFront=function(){h&&(u>0&&--u,h&&(h===d?h=d=void 0:(h=h.next)&&(h.pre=void 0)))},this.merge=function(f){var p=this,m=h;f.forEach(function(g){for(;m&&m.value!==void 0&&m.value<=g;)m=m.next;if(m===void 0)p.pushBack(g),m=d;else if(m===h)p.pushFront(g),m=h;else{++u;var _=m.pre;_&&(_.next=new a(g),_.next.pre=_,_.next.next=m,m&&(m.pre=_.next))}})},this[Symbol.iterator]=function(){return function(){var f;return n(this,function(p){switch(p.label){case 0:f=h,p.label=1;case 1:if(f===void 0)return[3,3];if(!f.value)throw new Error("unknown error");return[4,f.value];case 2:return p.sent(),f=f.next,[3,1];case 3:return[2]}})}()},l.forEach(function(f){return c.pushBack(f)}),Object.freeze(this)}Object.freeze(o),r.default=o},{}],30:[function(t,i,r){var n=this&&this.__generator||function(c,u){var h,d,f,p,m={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return p={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function g(_){return function(y){return function(v){if(h)throw new TypeError("Generator is already executing.");for(;m;)try{if(h=1,d&&(f=2&v[0]?d.return:v[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,v[1])).done)return f;switch(d=0,f&&(v=[2&v[0],f.value]),v[0]){case 0:case 1:f=v;break;case 4:return m.label++,{value:v[1],done:!1};case 5:m.label++,d=v[1],v=[0];continue;case 7:v=m.ops.pop(),m.trys.pop();continue;default:if(!(f=(f=m.trys).length>0&&f[f.length-1])&&(v[0]===6||v[0]===2)){m=0;continue}if(v[0]===3&&(!f||v[1]>f[0]&&v[1]=c.length&&(c=void 0),{value:c&&c[d++],done:!c}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../Base/TreeNode");function l(c,u){var h=this;c===void 0&&(c=[]),u=u||function(M,R){return MR?1:0};var d=0,f=new o.default;f.color=o.default.TreeNodeColorType.black,this.size=function(){return d},this.empty=function(){return d===0},this.clear=function(){d=0,f.key=f.value=void 0,f.leftChild=f.rightChild=f.brother=void 0};var p=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.leftChild?p(M.leftChild):M},m=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.rightChild?m(M.rightChild):M};this.front=function(){if(!this.empty()){var M=p(f);if(M.key===void 0||M.value===void 0)throw new Error("unknown error");return{key:M.key,value:M.value}}},this.back=function(){if(!this.empty()){var M=m(f);if(M.key===void 0||M.value===void 0)throw new Error("unknown error");return{key:M.key,value:M.value}}},this.forEach=function(M){var R,I,L=0;try{for(var k=a(this),V=k.next();!V.done;V=k.next())M(V.value,L++)}catch(H){R={error:H}}finally{try{V&&!V.done&&(I=k.return)&&I.call(k)}finally{if(R)throw R.error}}},this.getElementByPos=function(M){var R,I;if(M<0||M>=this.size())throw new Error("pos must more than 0 and less than set's size");var L=0;try{for(var k=a(this),V=k.next();!V.done;V=k.next()){var H=V.value;if(L===M)return H;++L}}catch(j){R={error:j}}finally{try{V&&!V.done&&(I=k.return)&&I.call(k)}finally{if(R)throw R.error}}throw new Error("unknown Error")};var g=function(M,R){if(M&&M.key!==void 0&&M.value!==void 0){var I=u(M.key,R);return I===0?{key:M.key,value:M.value}:I<0?g(M.rightChild,R):g(M.leftChild,R)||{key:M.key,value:M.value}}};this.lowerBound=function(M){return g(f,M)};var _=function(M,R){if(M&&M.key!==void 0&&M.value!==void 0)return u(M.key,R)<=0?_(M.rightChild,R):_(M.leftChild,R)||{key:M.key,value:M.value}};this.upperBound=function(M){return _(f,M)};var y=function(M,R){if(M&&M.key!==void 0&&M.value!==void 0){var I=u(M.key,R);return I===0?{key:M.key,value:M.value}:I>0?y(M.leftChild,R):y(M.rightChild,R)||{key:M.key,value:M.value}}};this.reverseLowerBound=function(M){return y(f,M)};var v=function(M,R){if(M&&M.key!==void 0&&M.value!==void 0)return u(M.key,R)>=0?v(M.leftChild,R):v(M.rightChild,R)||{key:M.key,value:M.value}};this.reverseUpperBound=function(M){return v(f,M)};var x=function(M){var R=M.parent;if(!R){if(M===f)return;throw new Error("unknown error")}if(M.color!==o.default.TreeNodeColorType.red){var I=M.brother;if(!I)throw new Error("unknown error");if(M===R.leftChild)if(I.color===o.default.TreeNodeColorType.red){I.color=o.default.TreeNodeColorType.black,R.color=o.default.TreeNodeColorType.red;var L=R.rotateLeft();f===R&&(f=L),x(M)}else I.color===o.default.TreeNodeColorType.black&&(I.rightChild&&I.rightChild.color===o.default.TreeNodeColorType.red?(I.color=R.color,R.color=o.default.TreeNodeColorType.black,I.rightChild&&(I.rightChild.color=o.default.TreeNodeColorType.black),L=R.rotateLeft(),f===R&&(f=L),M.color=o.default.TreeNodeColorType.black):I.rightChild&&I.rightChild.color!==o.default.TreeNodeColorType.black||!I.leftChild||I.leftChild.color!==o.default.TreeNodeColorType.red?I.leftChild&&I.leftChild.color!==o.default.TreeNodeColorType.black||I.rightChild&&I.rightChild.color!==o.default.TreeNodeColorType.black||(I.color=o.default.TreeNodeColorType.red,x(R)):(I.color=o.default.TreeNodeColorType.red,I.leftChild&&(I.leftChild.color=o.default.TreeNodeColorType.black),L=I.rotateRight(),f===I&&(f=L),x(M)));else M===R.rightChild&&(I.color===o.default.TreeNodeColorType.red?(I.color=o.default.TreeNodeColorType.black,R.color=o.default.TreeNodeColorType.red,L=R.rotateRight(),f===R&&(f=L),x(M)):I.color===o.default.TreeNodeColorType.black&&(I.leftChild&&I.leftChild.color===o.default.TreeNodeColorType.red?(I.color=R.color,R.color=o.default.TreeNodeColorType.black,I.leftChild&&(I.leftChild.color=o.default.TreeNodeColorType.black),L=R.rotateRight(),f===R&&(f=L),M.color=o.default.TreeNodeColorType.black):I.leftChild&&I.leftChild.color!==o.default.TreeNodeColorType.black||!I.rightChild||I.rightChild.color!==o.default.TreeNodeColorType.red?I.leftChild&&I.leftChild.color!==o.default.TreeNodeColorType.black||I.rightChild&&I.rightChild.color!==o.default.TreeNodeColorType.black||(I.color=o.default.TreeNodeColorType.red,x(R)):(I.color=o.default.TreeNodeColorType.red,I.rightChild&&(I.rightChild.color=o.default.TreeNodeColorType.black),L=I.rotateLeft(),f===I&&(f=L),x(M))))}else M.color=o.default.TreeNodeColorType.black},A=function(M){for(var R=M;R.leftChild||R.rightChild;){if(R.rightChild){R=p(R.rightChild);var I=M.key;M.key=R.key,R.key=I;var L=M.value;M.value=R.value,R.value=L,M=R}R.leftChild&&(R=m(R.leftChild),I=M.key,M.key=R.key,R.key=I,L=M.value,M.value=R.value,R.value=L,M=R)}x(R),R&&R.remove(),--d,f.color=o.default.TreeNodeColorType.black},b=function(M,R){return!(!M||M.key===void 0)&&(!!b(M.leftChild,R)||!!R(M)||b(M.rightChild,R))};this.eraseElementByPos=function(M){if(M<0||M>=d)throw new Error("pos must more than 0 and less than set's size");var R=0;b(f,function(I){return M===R?(A(I),!0):(++R,!1)})},this.eraseElementByKey=function(M){if(!this.empty()){var R=w(f,M);R!==void 0&&R.key!==void 0&&u(R.key,M)===0&&A(R)}};var C=function(M,R){if(!M||M.key===void 0)throw new Error("unknown error");var I=u(R,M.key);return I<0?M.leftChild?C(M.leftChild,R):(M.leftChild=new o.default,M.leftChild.parent=M,M.leftChild.brother=M.rightChild,M.rightChild&&(M.rightChild.brother=M.leftChild),M.leftChild):I>0?M.rightChild?C(M.rightChild,R):(M.rightChild=new o.default,M.rightChild.parent=M,M.rightChild.brother=M.leftChild,M.leftChild&&(M.leftChild.brother=M.rightChild),M.rightChild):M},T=function(M){var R=M.parent;if(!R){if(M===f)return;throw new Error("unknown error")}if(R.color!==o.default.TreeNodeColorType.black&&R.color===o.default.TreeNodeColorType.red){var I=R.brother,L=R.parent;if(!L)throw new Error("unknown error");if(I&&I.color===o.default.TreeNodeColorType.red)I.color=R.color=o.default.TreeNodeColorType.black,L.color=o.default.TreeNodeColorType.red,T(L);else if(!I||I.color===o.default.TreeNodeColorType.black)if(R===L.leftChild)if(M===R.leftChild){R.color=o.default.TreeNodeColorType.black,L.color=o.default.TreeNodeColorType.red;var k=L.rotateRight();L===f&&(f=k)}else M===R.rightChild&&(k=R.rotateLeft(),L===f&&(f=k),T(R));else R===L.rightChild&&(M===R.leftChild?(k=R.rotateRight(),L===f&&(f=k),T(R)):M===R.rightChild&&(R.color=o.default.TreeNodeColorType.black,L.color=o.default.TreeNodeColorType.red,k=L.rotateLeft(),L===f&&(f=k)))}};this.setElement=function(M,R){if(M==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(R!=null){if(this.empty())return++d,f.key=M,f.value=R,void(f.color=o.default.TreeNodeColorType.black);var I=C(f,M);I.key===void 0||u(I.key,M)!==0?(++d,I.key=M,I.value=R,T(I),f.color=o.default.TreeNodeColorType.black):I.value=R}else this.eraseElementByKey(M)};var w=function(M,R){if(M&&M.key!==void 0){var I=u(R,M.key);return I<0?w(M.leftChild,R):I>0?w(M.rightChild,R):M}};this.find=function(M){return!!w(f,M)},this.getElementByKey=function(M){var R=w(f,M);if((R==null?void 0:R.key)===void 0||(R==null?void 0:R.value)===void 0)throw new Error("unknown error");return R.value},this.union=function(M){var R=this;M.forEach(function(I){var L=I.key,k=I.value;return R.setElement(L,k)})},this.getHeight=function(){if(this.empty())return 0;var M=function(R){return R?Math.max(M(R.leftChild),M(R.rightChild))+1:1};return M(f)};var P=function(M){return n(this,function(R){switch(R.label){case 0:return M&&M.key!==void 0&&M.value!==void 0?[5,a(P(M.leftChild))]:[2];case 1:return R.sent(),[4,{key:M.key,value:M.value}];case 2:return R.sent(),[5,a(P(M.rightChild))];case 3:return R.sent(),[2]}})};this[Symbol.iterator]=function(){return P(f)},c.forEach(function(M){var R=M.key,I=M.value;return h.setElement(R,I)}),Object.freeze(this)}Object.freeze(l),r.default=l},{"../Base/TreeNode":25}],31:[function(t,i,r){function n(a,o){a===void 0&&(a=[]),o=o||function(d,f){return d>f?-1:d=c)throw new Error("unknown error");if(f<0||f>=c)throw new Error("unknown error");var p=l[d];l[d]=l[f],l[f]=p},h=function(d){if(d<0||d>=c)throw new Error("unknown error");var f=2*d+1,p=2*d+2;f0&&u(d,f),p0&&u(d,p)};(function(){for(var d=Math.floor((c-1)/2);d>=0;--d)for(var f=d,p=2*f+1;p0&&(g=m),o(l[f],l[g])<=0)break;u(f,g),p=2*(f=g)+1}})(),this.size=function(){return c},this.empty=function(){return c===0},this.clear=function(){c=0,l.length=0},this.push=function(d){if(l.push(d),++c!==1)for(var f=c-1;f>0;){var p=Math.floor((f-1)/2);if(o(l[p],d)<=0)break;h(p),f=p}},this.pop=function(){if(!this.empty())if(this.size()!==1){var d=l[c-1];--c;for(var f=0;f=this.size())break;var g=p;if(m0&&(g=m),o(l[g],d)>=0)break;l[f]=l[g],f=g}l[f]=d}else--c},this.top=function(){return l[0]},Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(n),r.default=n},{}],32:[function(t,i,r){Object.defineProperty(r,"__esModule",{value:!0});var n=t("../LinkList/LinkList");function a(o){o===void 0&&(o=[]);var l=new n.default(o);this.size=function(){return l.size()},this.empty=function(){return l.empty()},this.clear=function(){l.clear()},this.push=function(c){l.pushBack(c)},this.pop=function(){l.popFront()},this.front=function(){return l.front()},Object.freeze(this)}Object.freeze(a),r.default=a},{"../LinkList/LinkList":29}],33:[function(t,i,r){var n=this&&this.__generator||function(c,u){var h,d,f,p,m={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return p={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function g(_){return function(y){return function(v){if(h)throw new TypeError("Generator is already executing.");for(;m;)try{if(h=1,d&&(f=2&v[0]?d.return:v[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,v[1])).done)return f;switch(d=0,f&&(v=[2&v[0],f.value]),v[0]){case 0:case 1:f=v;break;case 4:return m.label++,{value:v[1],done:!1};case 5:m.label++,d=v[1],v=[0];continue;case 7:v=m.ops.pop(),m.trys.pop();continue;default:if(!(f=(f=m.trys).length>0&&f[f.length-1])&&(v[0]===6||v[0]===2)){m=0;continue}if(v[0]===3&&(!f||v[1]>f[0]&&v[1]=c.length&&(c=void 0),{value:c&&c[d++],done:!c}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var o=t("../Base/TreeNode");function l(c,u){var h=this;c===void 0&&(c=[]),u=u||function(M,R){return MR?1:0};var d=0,f=new o.default;f.color=o.default.TreeNodeColorType.black,this.size=function(){return d},this.empty=function(){return d===0},this.clear=function(){d=0,f.key=void 0,f.leftChild=f.rightChild=f.brother=f.parent=void 0,f.color=o.default.TreeNodeColorType.black};var p=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.leftChild?p(M.leftChild):M},m=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.rightChild?m(M.rightChild):M};this.front=function(){if(!this.empty())return p(f).key},this.back=function(){if(!this.empty())return m(f).key},this.forEach=function(M){var R,I,L=0;try{for(var k=a(this),V=k.next();!V.done;V=k.next())M(V.value,L++)}catch(H){R={error:H}}finally{try{V&&!V.done&&(I=k.return)&&I.call(k)}finally{if(R)throw R.error}}},this.getElementByPos=function(M){var R,I;if(M<0||M>=this.size())throw new Error("pos must more than 0 and less than set's size");var L=0;try{for(var k=a(this),V=k.next();!V.done;V=k.next()){var H=V.value;if(L===M)return H;++L}}catch(j){R={error:j}}finally{try{V&&!V.done&&(I=k.return)&&I.call(k)}finally{if(R)throw R.error}}throw new Error("unknown error")};var g=function(M){var R=M.parent;if(!R){if(M===f)return;throw new Error("unknown error")}if(M.color!==o.default.TreeNodeColorType.red){var I=M.brother;if(!I)throw new Error("unknown error");if(M===R.leftChild)if(I.color===o.default.TreeNodeColorType.red){I.color=o.default.TreeNodeColorType.black,R.color=o.default.TreeNodeColorType.red;var L=R.rotateLeft();f===R&&(f=L),g(M)}else I.color===o.default.TreeNodeColorType.black&&(I.rightChild&&I.rightChild.color===o.default.TreeNodeColorType.red?(I.color=R.color,R.color=o.default.TreeNodeColorType.black,I.rightChild&&(I.rightChild.color=o.default.TreeNodeColorType.black),L=R.rotateLeft(),f===R&&(f=L),M.color=o.default.TreeNodeColorType.black):I.rightChild&&I.rightChild.color!==o.default.TreeNodeColorType.black||!I.leftChild||I.leftChild.color!==o.default.TreeNodeColorType.red?I.leftChild&&I.leftChild.color!==o.default.TreeNodeColorType.black||I.rightChild&&I.rightChild.color!==o.default.TreeNodeColorType.black||(I.color=o.default.TreeNodeColorType.red,g(R)):(I.color=o.default.TreeNodeColorType.red,I.leftChild&&(I.leftChild.color=o.default.TreeNodeColorType.black),L=I.rotateRight(),f===I&&(f=L),g(M)));else M===R.rightChild&&(I.color===o.default.TreeNodeColorType.red?(I.color=o.default.TreeNodeColorType.black,R.color=o.default.TreeNodeColorType.red,L=R.rotateRight(),f===R&&(f=L),g(M)):I.color===o.default.TreeNodeColorType.black&&(I.leftChild&&I.leftChild.color===o.default.TreeNodeColorType.red?(I.color=R.color,R.color=o.default.TreeNodeColorType.black,I.leftChild&&(I.leftChild.color=o.default.TreeNodeColorType.black),L=R.rotateRight(),f===R&&(f=L),M.color=o.default.TreeNodeColorType.black):I.leftChild&&I.leftChild.color!==o.default.TreeNodeColorType.black||!I.rightChild||I.rightChild.color!==o.default.TreeNodeColorType.red?I.leftChild&&I.leftChild.color!==o.default.TreeNodeColorType.black||I.rightChild&&I.rightChild.color!==o.default.TreeNodeColorType.black||(I.color=o.default.TreeNodeColorType.red,g(R)):(I.color=o.default.TreeNodeColorType.red,I.rightChild&&(I.rightChild.color=o.default.TreeNodeColorType.black),L=I.rotateLeft(),f===I&&(f=L),g(M))))}else M.color=o.default.TreeNodeColorType.black},_=function(M){for(var R=M;R.leftChild||R.rightChild;){if(R.rightChild){R=p(R.rightChild);var I=M.key;M.key=R.key,R.key=I,M=R}R.leftChild&&(R=m(R.leftChild),I=M.key,M.key=R.key,R.key=I,M=R)}g(R),R&&R.remove(),--d,f.color=o.default.TreeNodeColorType.black},y=function(M,R){return!(!M||M.key===void 0)&&(!!y(M.leftChild,R)||!!R(M)||y(M.rightChild,R))};this.eraseElementByPos=function(M){if(M<0||M>=d)throw new Error("pos must more than 0 and less than set's size");var R=0;y(f,function(I){return M===R?(_(I),!0):(++R,!1)})},this.eraseElementByValue=function(M){if(!this.empty()){var R=A(f,M);R!==void 0&&R.key!==void 0&&u(R.key,M)===0&&_(R)}};var v=function(M,R){if(!M||M.key===void 0)throw new Error("unknown error");var I=u(R,M.key);return I<0?M.leftChild?v(M.leftChild,R):(M.leftChild=new o.default,M.leftChild.parent=M,M.leftChild.brother=M.rightChild,M.rightChild&&(M.rightChild.brother=M.leftChild),M.leftChild):I>0?M.rightChild?v(M.rightChild,R):(M.rightChild=new o.default,M.rightChild.parent=M,M.rightChild.brother=M.leftChild,M.leftChild&&(M.leftChild.brother=M.rightChild),M.rightChild):M},x=function(M){var R=M.parent;if(!R){if(M===f)return;throw new Error("unknown error")}if(R.color!==o.default.TreeNodeColorType.black&&R.color===o.default.TreeNodeColorType.red){var I=R.brother,L=R.parent;if(!L)throw new Error("unknown error");if(I&&I.color===o.default.TreeNodeColorType.red)I.color=R.color=o.default.TreeNodeColorType.black,L.color=o.default.TreeNodeColorType.red,x(L);else if(!I||I.color===o.default.TreeNodeColorType.black)if(R===L.leftChild)if(M===R.leftChild){R.color=o.default.TreeNodeColorType.black,L.color=o.default.TreeNodeColorType.red;var k=L.rotateRight();L===f&&(f=k)}else M===R.rightChild&&(k=R.rotateLeft(),L===f&&(f=k),x(R));else R===L.rightChild&&(M===R.leftChild?(k=R.rotateRight(),L===f&&(f=k),x(R)):M===R.rightChild&&(R.color=o.default.TreeNodeColorType.black,L.color=o.default.TreeNodeColorType.red,k=L.rotateLeft(),L===f&&(f=k)))}};this.insert=function(M){if(M==null)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++d,f.key=M,void(f.color=o.default.TreeNodeColorType.black);var R=v(f,M);R.key!==void 0&&u(R.key,M)===0||(++d,R.key=M,x(R),f.color=o.default.TreeNodeColorType.black)};var A=function(M,R){if(M&&M.key!==void 0){var I=u(R,M.key);return I<0?A(M.leftChild,R):I>0?A(M.rightChild,R):M}};this.find=function(M){var R=A(f,M);return R!==void 0&&R.key!==void 0&&u(R.key,M)===0};var b=function(M,R){if(M&&M.key!==void 0){var I=u(M.key,R);if(I===0)return M.key;if(I<0)return b(M.rightChild,R);var L=b(M.leftChild,R);return L!==void 0?L:M.key}};this.lowerBound=function(M){return b(f,M)};var C=function(M,R){if(M&&M.key!==void 0){if(u(M.key,R)<=0)return C(M.rightChild,R);var I=C(M.leftChild,R);return I!==void 0?I:M.key}};this.upperBound=function(M){return C(f,M)};var T=function(M,R){if(M&&M.key!==void 0){var I=u(M.key,R);if(I===0)return M.key;if(I>0)return T(M.leftChild,R);var L=T(M.rightChild,R);return L!==void 0?L:M.key}};this.reverseLowerBound=function(M){return T(f,M)};var w=function(M,R){if(M&&M.key!==void 0){if(u(M.key,R)>=0)return w(M.leftChild,R);var I=w(M.rightChild,R);return I!==void 0?I:M.key}};this.reverseUpperBound=function(M){return w(f,M)},this.union=function(M){var R=this;M.forEach(function(I){return R.insert(I)})},this.getHeight=function(){if(this.empty())return 0;var M=function(R){return R?Math.max(M(R.leftChild),M(R.rightChild))+1:1};return M(f)};var P=function(M){return n(this,function(R){switch(R.label){case 0:return M&&M.key!==void 0?[5,a(P(M.leftChild))]:[2];case 1:return R.sent(),[4,M.key];case 2:return R.sent(),[5,a(P(M.rightChild))];case 3:return R.sent(),[2]}})};this[Symbol.iterator]=function(){return P(f)},c.forEach(function(M){return h.insert(M)}),Object.freeze(this)}Object.freeze(l),r.default=l},{"../Base/TreeNode":25}],34:[function(t,i,r){function n(a){var o=this;a===void 0&&(a=[]);var l=0,c=[];this.size=function(){return l},this.empty=function(){return l===0},this.clear=function(){l=0,c.length=0},this.push=function(u){c.push(u),++l},this.pop=function(){c.pop(),l>0&&--l},this.top=function(){return c[l-1]},a.forEach(function(u){return o.push(u)}),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(n),r.default=n},{}],35:[function(t,i,r){var n=this&&this.__generator||function(u,h){var d,f,p,m,g={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return m={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function _(y){return function(v){return function(x){if(d)throw new TypeError("Generator is already executing.");for(;g;)try{if(d=1,f&&(p=2&x[0]?f.return:x[0]?f.throw||((p=f.return)&&p.call(f),0):f.next)&&!(p=p.call(f,x[1])).done)return p;switch(f=0,p&&(x=[2&x[0],p.value]),x[0]){case 0:case 1:p=x;break;case 4:return g.label++,{value:x[1],done:!1};case 5:g.label++,f=x[1],x=[0];continue;case 7:x=g.ops.pop(),g.trys.pop();continue;default:if(!(p=(p=g.trys).length>0&&p[p.length-1])&&(x[0]===6||x[0]===2)){g=0;continue}if(x[0]===3&&(!p||x[1]>p[0]&&x[1]0)&&!(f=m.next()).done;)g.push(f.value)}catch(_){p={error:_}}finally{try{f&&!f.done&&(d=m.return)&&d.call(m)}finally{if(p)throw p.error}}return g},o=this&&this.__spreadArray||function(u,h,d){if(d||arguments.length===2)for(var f,p=0,m=h.length;p=u.length&&(u=void 0),{value:u&&u[f++],done:!u}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};function c(u){var h=this;u===void 0&&(u=[]);var d=0,f=[];this.size=function(){return d},this.empty=function(){return d===0},this.clear=function(){d=0,f.length=0},this.front=function(){if(!this.empty())return f[0]},this.back=function(){if(!this.empty())return f[d-1]},this.forEach=function(p){f.forEach(p)},this.getElementByPos=function(p){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");return f[p]},this.eraseElementByPos=function(p){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");for(var m=p;mg;)this.popBack()},this.pushBack=function(p){f.push(p),++d},this.popBack=function(){f.pop(),d>0&&--d},this.setElementByPos=function(p,m){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");f[p]=m},this.insert=function(p,m,g){if(g===void 0&&(g=1),p<0||p>d)throw new Error("pos must more than 0 and less than or equal to vector's size");f.splice.apply(f,o([p,0],a(new Array(g).fill(m)),!1)),d+=g},this.find=function(p){return f.includes(p)},this.reverse=function(){f.reverse()},this.unique=function(){var p,m=[];this.forEach(function(_,y){y!==0&&_===p||(m.push(_),p=_)}),m.forEach(function(_,y){f[y]=_});for(var g=m.length;d>g;)this.popBack()},this.sort=function(p){f.sort(p)},this[Symbol.iterator]=function(){return function(){return n(this,function(p){switch(p.label){case 0:return[5,l(f)];case 1:return[2,p.sent()]}})}()},u.forEach(function(p){return h.pushBack(p)}),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(c),r.default=c},{}],36:[function(t,i,r){Object.defineProperty(r,"__esModule",{value:!0}),r.HashMap=r.HashSet=r.Map=r.Set=r.PriorityQueue=r.Deque=r.LinkList=r.Queue=r.Stack=r.Vector=void 0;var n=t("./Vector/Vector");r.Vector=n.default;var a=t("./Stack/Stack");r.Stack=a.default;var o=t("./Queue/Queue");r.Queue=o.default;var l=t("./LinkList/LinkList");r.LinkList=l.default;var c=t("./Deque/Deque");r.Deque=c.default;var u=t("./PriorityQueue/PriorityQueue");r.PriorityQueue=u.default;var h=t("./Set/Set");r.Set=h.default;var d=t("./Map/Map");r.Map=d.default;var f=t("./HashSet/HashSet");r.HashSet=f.default;var p=t("./HashMap/HashMap");r.HashMap=p.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(t,i,r){const n=t("yallist"),a=Symbol("max"),o=Symbol("length"),l=Symbol("lengthCalculator"),c=Symbol("allowStale"),u=Symbol("maxAge"),h=Symbol("dispose"),d=Symbol("noDisposeOnSet"),f=Symbol("lruList"),p=Symbol("cache"),m=Symbol("updateAgeOnGet"),g=()=>1,_=(C,T,w)=>{const P=C[p].get(T);if(P){const M=P.value;if(y(C,M)){if(x(C,P),!C[c])return}else w&&(C[m]&&(P.value.now=Date.now()),C[f].unshiftNode(P));return M.value}},y=(C,T)=>{if(!T||!T.maxAge&&!C[u])return!1;const w=Date.now()-T.now;return T.maxAge?w>T.maxAge:C[u]&&w>C[u]},v=C=>{if(C[o]>C[a])for(let T=C[f].tail;C[o]>C[a]&&T!==null;){const w=T.prev;x(C,T),T=w}},x=(C,T)=>{if(T){const w=T.value;C[h]&&C[h](w.key,w.value),C[o]-=w.length,C[p].delete(w.key),C[f].removeNode(T)}};class A{constructor(T,w,P,M,R){this.key=T,this.value=w,this.length=P,this.now=M,this.maxAge=R||0}}const b=(C,T,w,P)=>{let M=w.value;y(C,M)&&(x(C,w),C[c]||(M=void 0)),M&&T.call(P,M.value,M.key,C)};i.exports=class{constructor(C){if(typeof C=="number"&&(C={max:C}),C||(C={}),C.max&&(typeof C.max!="number"||C.max<0))throw new TypeError("max must be a non-negative number");this[a]=C.max||1/0;const T=C.length||g;if(this[l]=typeof T!="function"?g:T,this[c]=C.stale||!1,C.maxAge&&typeof C.maxAge!="number")throw new TypeError("maxAge must be a number");this[u]=C.maxAge||0,this[h]=C.dispose,this[d]=C.noDisposeOnSet||!1,this[m]=C.updateAgeOnGet||!1,this.reset()}set max(C){if(typeof C!="number"||C<0)throw new TypeError("max must be a non-negative number");this[a]=C||1/0,v(this)}get max(){return this[a]}set allowStale(C){this[c]=!!C}get allowStale(){return this[c]}set maxAge(C){if(typeof C!="number")throw new TypeError("maxAge must be a non-negative number");this[u]=C,v(this)}get maxAge(){return this[u]}set lengthCalculator(C){typeof C!="function"&&(C=g),C!==this[l]&&(this[l]=C,this[o]=0,this[f].forEach(T=>{T.length=this[l](T.value,T.key),this[o]+=T.length})),v(this)}get lengthCalculator(){return this[l]}get length(){return this[o]}get itemCount(){return this[f].length}rforEach(C,T){T=T||this;for(let w=this[f].tail;w!==null;){const P=w.prev;b(this,C,w,T),w=P}}forEach(C,T){T=T||this;for(let w=this[f].head;w!==null;){const P=w.next;b(this,C,w,T),w=P}}keys(){return this[f].toArray().map(C=>C.key)}values(){return this[f].toArray().map(C=>C.value)}reset(){this[h]&&this[f]&&this[f].length&&this[f].forEach(C=>this[h](C.key,C.value)),this[p]=new Map,this[f]=new n,this[o]=0}dump(){return this[f].map(C=>!y(this,C)&&{k:C.key,v:C.value,e:C.now+(C.maxAge||0)}).toArray().filter(C=>C)}dumpLru(){return this[f]}set(C,T,w){if((w=w||this[u])&&typeof w!="number")throw new TypeError("maxAge must be a number");const P=w?Date.now():0,M=this[l](T,C);if(this[p].has(C)){if(M>this[a])return x(this,this[p].get(C)),!1;const I=this[p].get(C).value;return this[h]&&(this[d]||this[h](C,I.value)),I.now=P,I.maxAge=w,I.value=T,this[o]+=M-I.length,I.length=M,this.get(C),v(this),!0}const R=new A(C,T,M,P,w);return R.length>this[a]?(this[h]&&this[h](C,T),!1):(this[o]+=R.length,this[f].unshift(R),this[p].set(C,this[f].head),v(this),!0)}has(C){if(!this[p].has(C))return!1;const T=this[p].get(C).value;return!y(this,T)}get(C){return _(this,C,!0)}peek(C){return _(this,C,!1)}pop(){const C=this[f].tail;return C?(x(this,C),C.value):null}del(C){x(this,this[p].get(C))}load(C){this.reset();const T=Date.now();for(let w=C.length-1;w>=0;w--){const P=C[w],M=P.e||0;if(M===0)this.set(P.k,P.v);else{const R=M-T;R>0&&this.set(P.k,P.v,R)}}}prune(){this[p].forEach((C,T)=>_(this,T,!1))}}},{yallist:83}],38:[function(t,i,r){(function(n){(function(){const a=i.exports;a.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},a.codes={};for(const l in a.types){const c=a.types[l];a.codes[c]=l}a.CMD_SHIFT=4,a.CMD_MASK=240,a.DUP_MASK=8,a.QOS_MASK=3,a.QOS_SHIFT=1,a.RETAIN_MASK=1,a.VARBYTEINT_MASK=127,a.VARBYTEINT_FIN_MASK=128,a.VARBYTEINT_MAX=268435455,a.SESSIONPRESENT_MASK=1,a.SESSIONPRESENT_HEADER=n.from([a.SESSIONPRESENT_MASK]),a.CONNACK_HEADER=n.from([a.codes.connack<[0,1].map(u=>[0,1].map(h=>{const d=n.alloc(1);return d.writeUInt8(a.codes[l]<n.from([l])),a.EMPTY={pingreq:n.from([a.codes.pingreq<<4,0]),pingresp:n.from([a.codes.pingresp<<4,0]),disconnect:n.from([a.codes.disconnect<<4,0])}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],39:[function(t,i,r){(function(n){(function(){const a=t("./writeToStream"),o=t("events");class l extends o{constructor(){super(),this._array=new Array(20),this._i=0}write(u){return this._array[this._i++]=u,!0}concat(){let u=0;const h=new Array(this._array.length),d=this._array;let f,p=0;for(f=0;f>8,0),h.writeUInt8(255&u,1),h}i.exports={cache:o,generateCache:function(){for(let u=0;u<65536;u++)o[u]=c(u)},generateNumber:c,genBufVariableByteInt:function(u){let h=0,d=0;const f=n.allocUnsafe(4);do h=u%128|0,(u=u/128|0)>0&&(h|=128),f.writeUInt8(h,d++);while(u>0&&d<4);return u>0&&(d=0),l?f.subarray(0,d):f.slice(0,d)},generate4ByteBuffer:function(u){const h=n.allocUnsafe(4);return h.writeUInt32BE(u,0),h}}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],42:[function(t,i,r){i.exports=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}},{}],43:[function(t,i,r){const n=t("bl"),a=t("events"),o=t("./packet"),l=t("./constants"),c=t("debug")("mqtt-packet:parser");class u extends a{constructor(){super(),this.parser=this.constructor.parser}static parser(d){return this instanceof u?(this.settings=d||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new u().parser(d)}_resetState(){c("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=n(),this._stateCounter=0}parse(d){for(this.error&&this._resetState(),this._list.append(d),c("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,c("parse: state complete. _stateCounter is now: %d",this._stateCounter),c("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return c("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const d=this._list.readUInt8(0);return this.packet.cmd=l.types[d>>l.CMD_SHIFT],this.packet.retain=(d&l.RETAIN_MASK)!=0,this.packet.qos=d>>l.QOS_SHIFT&l.QOS_MASK,this.packet.dup=(d&l.DUP_MASK)!=0,c("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const d=this._parseVarByteNum(!0);return d&&(this.packet.length=d.value,this._list.consume(d.bytes)),c("_parseLength %d",d.value),!!d}_parsePayload(){c("_parsePayload: payload %O",this._list);let d=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}d=!0}return c("_parsePayload complete result: %s",d),d}_parseConnect(){let d,f,p,m;c("_parseConnect");const g={},_=this.packet,y=this._parseString();if(y===null)return this._emitError(new Error("Cannot parse protocolId"));if(y!=="MQTT"&&y!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(_.protocolId=y,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(_.protocolVersion=this._list.readUInt8(this._pos),_.protocolVersion>=128&&(_.bridgeMode=!0,_.protocolVersion=_.protocolVersion-128),_.protocolVersion!==3&&_.protocolVersion!==4&&_.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(g.username=this._list.readUInt8(this._pos)&l.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&l.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&l.WILL_FLAG_MASK,g.will&&(_.will={},_.will.retain=(this._list.readUInt8(this._pos)&l.WILL_RETAIN_MASK)!=0,_.will.qos=(this._list.readUInt8(this._pos)&l.WILL_QOS_MASK)>>l.WILL_QOS_SHIFT),_.clean=(this._list.readUInt8(this._pos)&l.CLEAN_SESSION_MASK)!=0,this._pos++,_.keepalive=this._parseNum(),_.keepalive===-1)return this._emitError(new Error("Packet too short"));if(_.protocolVersion===5){const x=this._parseProperties();Object.getOwnPropertyNames(x).length&&(_.properties=x)}const v=this._parseString();if(v===null)return this._emitError(new Error("Packet too short"));if(_.clientId=v,c("_parseConnect: packet.clientId: %s",_.clientId),g.will){if(_.protocolVersion===5){const x=this._parseProperties();Object.getOwnPropertyNames(x).length&&(_.will.properties=x)}if((d=this._parseString())===null)return this._emitError(new Error("Cannot parse will topic"));if(_.will.topic=d,c("_parseConnect: packet.will.topic: %s",_.will.topic),(f=this._parseBuffer())===null)return this._emitError(new Error("Cannot parse will payload"));_.will.payload=f,c("_parseConnect: packet.will.paylaod: %s",_.will.payload)}if(g.username){if((m=this._parseString())===null)return this._emitError(new Error("Cannot parse username"));_.username=m,c("_parseConnect: packet.username: %s",_.username)}if(g.password){if((p=this._parseBuffer())===null)return this._emitError(new Error("Cannot parse password"));_.password=p}return this.settings=_,c("_parseConnect: complete"),_}_parseConnack(){c("_parseConnack");const d=this.packet;if(this._list.length<1)return null;if(d.sessionPresent=!!(this._list.readUInt8(this._pos++)&l.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?d.reasonCode=this._list.readUInt8(this._pos++):d.reasonCode=0;else{if(this._list.length<2)return null;d.returnCode=this._list.readUInt8(this._pos++)}if(d.returnCode===-1||d.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}c("_parseConnack: complete")}_parsePublish(){c("_parsePublish");const d=this.packet;if(d.topic=this._parseString(),d.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(d.qos>0)||this._parseMessageId()){if(this.settings.protocolVersion===5){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}d.payload=this._list.slice(this._pos,d.length),c("_parsePublish: payload from buffer list: %o",d.payload)}}_parseSubscribe(){c("_parseSubscribe");const d=this.packet;let f,p,m,g,_,y,v;if(d.qos!==1)return this._emitError(new Error("Wrong subscribe header"));if(d.subscriptions=[],this._parseMessageId()){if(this.settings.protocolVersion===5){const x=this._parseProperties();Object.getOwnPropertyNames(x).length&&(d.properties=x)}for(;this._pos=d.length)return this._emitError(new Error("Malformed Subscribe Payload"));m=(p=this._parseByte())&l.SUBSCRIBE_OPTIONS_QOS_MASK,y=(p>>l.SUBSCRIBE_OPTIONS_NL_SHIFT&l.SUBSCRIBE_OPTIONS_NL_MASK)!=0,_=(p>>l.SUBSCRIBE_OPTIONS_RAP_SHIFT&l.SUBSCRIBE_OPTIONS_RAP_MASK)!=0,g=p>>l.SUBSCRIBE_OPTIONS_RH_SHIFT&l.SUBSCRIBE_OPTIONS_RH_MASK,v={topic:f,qos:m},this.settings.protocolVersion===5?(v.nl=y,v.rap=_,v.rh=g):this.settings.bridgeMode&&(v.rh=0,v.rap=!0,v.nl=!0),c("_parseSubscribe: push subscription `%s` to subscription",v),d.subscriptions.push(v)}}}_parseSuback(){c("_parseSuback");const d=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(this.settings.protocolVersion===5){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}for(;this._pos2?(d.reasonCode=this._parseByte(),c("_parseConfirmation: packet.reasonCode `%d`",d.reasonCode)):d.reasonCode=0,d.length>3)){const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}return!0}_parseDisconnect(){const d=this.packet;if(c("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?d.reasonCode=this._parseByte():d.reasonCode=0;const f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(d.properties=f)}return c("_parseDisconnect result: true"),!0}_parseAuth(){c("_parseAuth");const d=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));d.reasonCode=this._parseByte();const f=this._parseProperties();return Object.getOwnPropertyNames(f).length&&(d.properties=f),c("_parseAuth: result: true"),!0}_parseMessageId(){const d=this.packet;return d.messageId=this._parseNum(),d.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(c("_parseMessageId: packet.messageId %d",d.messageId),!0)}_parseString(d){const f=this._parseNum(),p=f+this._pos;if(f===-1||p>this._list.length||p>this.packet.length)return null;const m=this._list.toString("utf8",this._pos,p);return this._pos+=f,c("_parseString: result: %s",m),m}_parseStringPair(){return c("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const d=this._parseNum(),f=d+this._pos;if(d===-1||f>this._list.length||f>this.packet.length)return null;const p=this._list.slice(this._pos,f);return this._pos+=d,c("_parseBuffer: result: %o",p),p}_parseNum(){if(this._list.length-this._pos<2)return-1;const d=this._list.readUInt16BE(this._pos);return this._pos+=2,c("_parseNum: result: %s",d),d}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const d=this._list.readUInt32BE(this._pos);return this._pos+=4,c("_parse4ByteNum: result: %s",d),d}_parseVarByteNum(d){c("_parseVarByteNum");let f,p=0,m=1,g=0,_=!1;const y=this._pos?this._pos:0;for(;p<4&&y+p=p&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=p),c("_parseVarByteNum: result: %o",_=!!_&&(d?{bytes:p,value:g}:g)),_}_parseByte(){let d;return this._pos=4)&&(B||ce))ne+=n.byteLength(B)+2;else{if(ae<4)return W.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*ce==0)return W.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof N!="number"||N<0||N>65535||N%1!=0)return W.emit("error",new Error("Invalid keepalive")),!1;if(ne+=2,ne+=1,ae===5){var pe=R(W,oe);if(!pe)return!1;ne+=pe.length}if(ue){if(typeof ue!="object")return W.emit("error",new Error("Invalid will")),!1;if(!ue.topic||typeof ue.topic!="string")return W.emit("error",new Error("Invalid will topic")),!1;if(ne+=n.byteLength(ue.topic)+2,ne+=2,ue.payload){if(!(ue.payload.length>=0))return W.emit("error",new Error("Invalid will payload")),!1;typeof ue.payload=="string"?ne+=n.byteLength(ue.payload):ne+=ue.payload.length}var ye={};if(ae===5){if(!(ye=R(W,ue.properties)))return!1;ne+=ye.length}}let Ie=!1;if(Y!=null){if(!H(Y))return W.emit("error",new Error("Invalid username")),!1;Ie=!0,ne+=n.byteLength(Y)+2}if(te!=null){if(!Ie)return W.emit("error",new Error("Username is required to use password")),!1;if(!H(te))return W.emit("error",new Error("Invalid password")),!1;ne+=V(te)+2}W.write(a.CONNECT_HEADER),b(W,ne),M(W,ie),q.bridgeMode&&(ae+=128),W.write(ae===131?a.VERSION131:ae===132?a.VERSION132:ae===4?a.VERSION4:ae===5?a.VERSION5:a.VERSION3);let Ne=0;return Ne|=Y!=null?a.USERNAME_MASK:0,Ne|=te!=null?a.PASSWORD_MASK:0,Ne|=ue&&ue.retain?a.WILL_RETAIN_MASK:0,Ne|=ue&&ue.qos?ue.qos<0&&_(W,B),oe!=null&&oe.write(),h("publish: payload: %o",N),W.write(N)}(j,z,K);case"puback":case"pubrec":case"pubrel":case"pubcomp":return function(U,W,Z){const q=Z?Z.protocolVersion:4,ie=U||{},ae=ie.cmd||"puback",ue=ie.messageId,ce=ie.dup&&ae==="pubrel"?a.DUP_MASK:0;let N=0;const B=ie.reasonCode,Y=ie.properties;let te=q===5?3:2;if(ae==="pubrel"&&(N=1),typeof ue!="number")return W.emit("error",new Error("Invalid messageId")),!1;let oe=null;if(q===5&&typeof Y=="object"){if(!(oe=I(W,Y,Z,te)))return!1;te+=oe.length}return W.write(a.ACKS[ae][N][ce][0]),b(W,te),_(W,ue),q===5&&W.write(n.from([B])),oe!==null&&oe.write(),!0}(j,z,K);case"subscribe":return function(U,W,Z){h("subscribe: packet: ");const q=Z?Z.protocolVersion:4,ie=U||{},ae=ie.dup?a.DUP_MASK:0,ue=ie.messageId,ce=ie.subscriptions,N=ie.properties;let B=0;if(typeof ue!="number")return W.emit("error",new Error("Invalid messageId")),!1;B+=2;let Y=null;if(q===5){if(!(Y=R(W,N)))return!1;B+=Y.length}if(typeof ce!="object"||!ce.length)return W.emit("error",new Error("Invalid subscriptions")),!1;for(let oe=0;oe2)return W.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}B+=n.byteLength(ne)+2+1}h("subscribe: writing to stream: %o",a.SUBSCRIBE_HEADER),W.write(a.SUBSCRIBE_HEADER[1][ae?1:0][0]),b(W,B),_(W,ue),Y!==null&&Y.write();let te=!0;for(const oe of ce){const ne=oe.topic,pe=oe.qos,ye=+oe.nl,Ie=+oe.rap,Ne=oe.rh;let Ve;C(W,ne),Ve=a.SUBSCRIBE_OPTIONS_QOS[pe],q===5&&(Ve|=ye?a.SUBSCRIBE_OPTIONS_NL:0,Ve|=Ie?a.SUBSCRIBE_OPTIONS_RAP:0,Ve|=Ne?a.SUBSCRIBE_OPTIONS_RH[Ne]:0),te=W.write(n.from([Ve]))}return te}(j,z,K);case"suback":return function(U,W,Z){const q=Z?Z.protocolVersion:4,ie=U||{},ae=ie.messageId,ue=ie.granted,ce=ie.properties;let N=0;if(typeof ae!="number")return W.emit("error",new Error("Invalid messageId")),!1;if(N+=2,typeof ue!="object"||!ue.length)return W.emit("error",new Error("Invalid qos vector")),!1;for(let Y=0;Y_===w,set(j){j?(d&&Object.keys(d).length!==0||(y=!0),_=w):(y=!1,_=P)}});const A={};function b(j,z){if(z>a.VARBYTEINT_MAX)return j.emit("error",new Error(`Invalid variable byte integer: ${z}`)),!1;let K=A[z];return K||(K=m(z),z<16384&&(A[z]=K)),h("writeVarByteInt: writing to stream: %o",K),j.write(K)}function C(j,z){const K=n.byteLength(z);return _(j,K),h("writeString: %s",z),j.write(z,"utf8")}function T(j,z,K){C(j,z),C(j,K)}function w(j,z){return h("writeNumberCached: number: %d",z),h("writeNumberCached: %o",d[z]),j.write(d[z])}function P(j,z){const K=f(z);return h("writeNumberGenerated: %o",K),j.write(K)}function M(j,z){typeof z=="string"?C(j,z):z?(_(j,z.length),j.write(z)):_(j,0)}function R(j,z){if(typeof z!="object"||z.length!=null)return{length:1,write(){k(j,{},0)}};let K=0;function U(W,Z){let q=0;switch(a.propertiesTypes[W]){case"byte":if(typeof Z!="boolean")return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=2;break;case"int8":if(typeof Z!="number"||Z<0||Z>255)return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=2;break;case"binary":if(Z&&Z===null)return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=1+n.byteLength(Z)+2;break;case"int16":if(typeof Z!="number"||Z<0||Z>65535)return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=3;break;case"int32":if(typeof Z!="number"||Z<0||Z>4294967295)return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=5;break;case"var":if(typeof Z!="number"||Z<0||Z>268435455)return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=1+n.byteLength(m(Z));break;case"string":if(typeof Z!="string")return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=3+n.byteLength(Z.toString());break;case"pair":if(typeof Z!="object")return j.emit("error",new Error(`Invalid ${W}: ${Z}`)),!1;q+=Object.getOwnPropertyNames(Z).reduce((ie,ae)=>{const ue=Z[ae];return Array.isArray(ue)?ie+=ue.reduce((ce,N)=>ce+=3+n.byteLength(ae.toString())+2+n.byteLength(N.toString()),0):ie+=3+n.byteLength(ae.toString())+2+n.byteLength(Z[ae].toString()),ie},0);break;default:return j.emit("error",new Error(`Invalid property ${W}: ${Z}`)),!1}return q}if(z)for(const W in z){let Z=0,q=0;const ie=z[W];if(Array.isArray(ie))for(let ae=0;aeZ;){const ie=W.shift();if(!ie||!z[ie])return!1;delete z[ie],q=R(j,z)}return q}function L(j,z,K){switch(a.propertiesTypes[z]){case"byte":j.write(n.from([a.properties[z]])),j.write(n.from([+K]));break;case"int8":j.write(n.from([a.properties[z]])),j.write(n.from([K]));break;case"binary":j.write(n.from([a.properties[z]])),M(j,K);break;case"int16":j.write(n.from([a.properties[z]])),_(j,K);break;case"int32":j.write(n.from([a.properties[z]])),function(U,W){const Z=g(W);h("write4ByteNumber: %o",Z),U.write(Z)}(j,K);break;case"var":j.write(n.from([a.properties[z]])),b(j,K);break;case"string":j.write(n.from([a.properties[z]])),C(j,K);break;case"pair":Object.getOwnPropertyNames(K).forEach(U=>{const W=K[U];Array.isArray(W)?W.forEach(Z=>{j.write(n.from([a.properties[z]])),T(j,U.toString(),Z.toString())}):(j.write(n.from([a.properties[z]])),T(j,U.toString(),W.toString()))});break;default:return j.emit("error",new Error(`Invalid property ${z} value: ${K}`)),!1}}function k(j,z,K){b(j,K);for(const U in z)if(Object.prototype.hasOwnProperty.call(z,U)&&z[U]!==null){const W=z[U];if(Array.isArray(W))for(let Z=0;Z=1.5*p;return Math.round(d/p)+" "+m+(g?"s":"")}i.exports=function(d,f){f=f||{};var p=typeof d;if(p==="string"&&d.length>0)return function(m){if(!((m=String(m)).length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(m);if(g){var _=parseFloat(g[1]);switch((g[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return _*u;case"weeks":case"week":case"w":return _*c;case"days":case"day":case"d":return _*l;case"hours":case"hour":case"hrs":case"hr":case"h":return _*o;case"minutes":case"minute":case"mins":case"min":case"m":return _*a;case"seconds":case"second":case"secs":case"sec":case"s":return _*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return _;default:return}}}}(d);if(p==="number"&&isFinite(d))return f.long?function(m){var g=Math.abs(m);return g>=l?h(m,g,l,"day"):g>=o?h(m,g,o,"hour"):g>=a?h(m,g,a,"minute"):g>=n?h(m,g,n,"second"):m+" ms"}(d):function(m){var g=Math.abs(m);return g>=l?Math.round(m/l)+"d":g>=o?Math.round(m/o)+"h":g>=a?Math.round(m/a)+"m":g>=n?Math.round(m/n)+"s":m+"ms"}(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))}},{}],46:[function(t,i,r){const n=t("./lib/number-allocator.js");i.exports.NumberAllocator=n},{"./lib/number-allocator.js":47}],47:[function(t,i,r){const n=t("js-sdsl").Set,a=t("debug")("number-allocator:trace"),o=t("debug")("number-allocator:error");function l(u,h){this.low=u,this.high=h}function c(u,h){if(!(this instanceof c))return new c(u,h);this.min=u,this.max=h,this.ss=new n([],(d,f)=>d.compare(f)),a("Create"),this.clear()}l.prototype.equals=function(u){return this.low===u.low&&this.high===u.high},l.prototype.compare=function(u){return this.lowu)return!1;if(d.low===u)return++d.low,a("use():"+u),!0;if(d.high===u)return--d.high,a("use():"+u),!0;const f=d.low;return d.low=u+1,this.ss.insert(new l(f,u-1)),a("use():"+u),!0}return a("use():failed"),!1},c.prototype.free=function(u){if(uthis.max)return void o("free():"+u+" is out of range");const h=new l(u,u),d=this.ss.lowerBound(h);if(d){if(d.low<=u&&u<=d.high)return void o("free():"+u+" has already been vacant");if(d===this.ss.front())u+1===d.low?--d.low:this.ss.insert(h);else{const f=this.ss.reverseLowerBound(h);f.high+1===u?u+1===d.low?(this.ss.eraseElementByValue(f),d.low=f.low):f.high=u:u+1===d.low?d.low=u:this.ss.insert(h)}}else{if(d===this.ss.front())return void this.ss.insert(h);const f=this.ss.reverseLowerBound(h);f.high+1===u?f.high=u:this.ss.insert(h)}a("free():"+u)},c.prototype.clear=function(){a("clear()"),this.ss.clear(),this.ss.insert(new l(this.min,this.max))},c.prototype.intervalCount=function(){return this.ss.size()},c.prototype.dump=function(){console.log("length:"+this.ss.size());for(const u of this.ss)console.log(u)},i.exports=c},{debug:18,"js-sdsl":36}],48:[function(t,i,r){var n=t("wrappy");function a(l){var c=function(){return c.called?c.value:(c.called=!0,c.value=l.apply(this,arguments))};return c.called=!1,c}function o(l){var c=function(){if(c.called)throw new Error(c.onceError);return c.called=!0,c.value=l.apply(this,arguments)},u=l.name||"Function wrapped with `once`";return c.onceError=u+" shouldn't be called more than once",c.called=!1,c}i.exports=n(a),i.exports.strict=n(o),a.proto=a(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return a(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return o(this)},configurable:!0})})},{wrappy:79}],49:[function(t,i,r){(function(n){(function(){n===void 0||!n.version||n.version.indexOf("v0.")===0||n.version.indexOf("v1.")===0&&n.version.indexOf("v1.8.")!==0?i.exports={nextTick:function(a,o,l,c){if(typeof a!="function")throw new TypeError('"callback" argument must be a function');var u,h,d=arguments.length;switch(d){case 0:case 1:return n.nextTick(a);case 2:return n.nextTick(function(){a.call(null,o)});case 3:return n.nextTick(function(){a.call(null,o,l)});case 4:return n.nextTick(function(){a.call(null,o,l,c)});default:for(u=new Array(d-1),h=0;h1)for(var A=1;A= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=f-p,P=Math.floor,M=String.fromCharCode;function R(U){throw new RangeError(T[U])}function I(U,W){for(var Z=U.length,q=[];Z--;)q[Z]=W(U[Z]);return q}function L(U,W){var Z=U.split("@"),q="";return Z.length>1&&(q=Z[0]+"@",U=Z[1]),q+I((U=U.replace(C,".")).split("."),W).join(".")}function k(U){for(var W,Z,q=[],ie=0,ae=U.length;ie=55296&&W<=56319&&ie65535&&(Z+=M((W-=65536)>>>10&1023|55296),W=56320|1023&W),Z+=M(W)}).join("")}function H(U,W){return U+22+75*(U<26)-((W!=0)<<5)}function j(U,W,Z){var q=0;for(U=Z?P(U/_):U>>1,U+=P(U/W);U>w*m>>1;q+=f)U=P(U/w);return P(q+(w+1)*U/(U+g))}function z(U){var W,Z,q,ie,ae,ue,ce,N,B,Y,te,oe=[],ne=U.length,pe=0,ye=v,Ie=y;for((Z=U.lastIndexOf(x))<0&&(Z=0),q=0;q=128&&R("not-basic"),oe.push(U.charCodeAt(q));for(ie=Z>0?Z+1:0;ie=ne&&R("invalid-input"),((N=(te=U.charCodeAt(ie++))-48<10?te-22:te-65<26?te-65:te-97<26?te-97:f)>=f||N>P((d-pe)/ue))&&R("overflow"),pe+=N*ue,!(N<(B=ce<=Ie?p:ce>=Ie+m?m:ce-Ie));ce+=f)ue>P(d/(Y=f-B))&&R("overflow"),ue*=Y;Ie=j(pe-ae,W=oe.length+1,ae==0),P(pe/W)>d-ye&&R("overflow"),ye+=P(pe/W),pe%=W,oe.splice(pe++,0,ye)}return V(oe)}function K(U){var W,Z,q,ie,ae,ue,ce,N,B,Y,te,oe,ne,pe,ye,Ie=[];for(oe=(U=k(U)).length,W=v,Z=0,ae=y,ue=0;ue=W&&teP((d-Z)/(ne=q+1))&&R("overflow"),Z+=(ce-W)*ne,W=ce,ue=0;ued&&R("overflow"),te==W){for(N=Z,B=f;!(N<(Y=B<=ae?p:B>=ae+m?m:B-ae));B+=f)ye=N-Y,pe=f-Y,Ie.push(M(H(Y+ye%pe,0))),N=P(ye/pe);Ie.push(M(H(N,0))),ae=j(Z,ne,q==ie),Z=0,++q}++Z,++W}return Ie.join("")}if(u={version:"1.4.1",ucs2:{decode:k,encode:V},decode:z,encode:K,toASCII:function(U){return L(U,function(W){return b.test(W)?"xn--"+K(W):W})},toUnicode:function(U){return L(U,function(W){return A.test(W)?z(W.slice(4).toLowerCase()):W})}},o&&l)if(i.exports==o)l.exports=u;else for(h in u)u.hasOwnProperty(h)&&(o[h]=u[h]);else a.punycode=u})(this)}).call(this)}).call(this,typeof Xt<"u"?Xt:typeof self<"u"?self:typeof window<"u"?window:{})},{}],52:[function(t,i,r){function n(o,l){return Object.prototype.hasOwnProperty.call(o,l)}i.exports=function(o,l,c,u){l=l||"&",c=c||"=";var h={};if(typeof o!="string"||o.length===0)return h;var d=/\+/g;o=o.split(l);var f=1e3;u&&typeof u.maxKeys=="number"&&(f=u.maxKeys);var p=o.length;f>0&&p>f&&(p=f);for(var m=0;m=0?(g=x.substr(0,A),_=x.substr(A+1)):(g=x,_=""),y=decodeURIComponent(g),v=decodeURIComponent(_),n(h,y)?a(h[y])?h[y].push(v):h[y]=[h[y],v]:h[y]=v}return h};var a=Array.isArray||function(o){return Object.prototype.toString.call(o)==="[object Array]"}},{}],53:[function(t,i,r){var n=function(c){switch(typeof c){case"string":return c;case"boolean":return c?"true":"false";case"number":return isFinite(c)?c:"";default:return""}};i.exports=function(c,u,h,d){return u=u||"&",h=h||"=",c===null&&(c=void 0),typeof c=="object"?o(l(c),function(f){var p=encodeURIComponent(n(f))+h;return a(c[f])?o(c[f],function(m){return p+encodeURIComponent(n(m))}).join(u):p+encodeURIComponent(n(c[f]))}).join(u):d?encodeURIComponent(n(d))+h+encodeURIComponent(n(c)):""};var a=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"};function o(c,u){if(c.map)return c.map(u);for(var h=[],d=0;d2?"one of ".concat(c," ").concat(l.slice(0,u-1).join(", "),", or ")+l[u-1]:u===2?"one of ".concat(c," ").concat(l[0]," or ").concat(l[1]):"of ".concat(c," ").concat(l[0])}return"of ".concat(c," ").concat(String(l))}a("ERR_INVALID_OPT_VALUE",function(l,c){return'The value "'+c+'" is invalid for option "'+l+'"'},TypeError),a("ERR_INVALID_ARG_TYPE",function(l,c,u){var h,d,f;if(typeof c=="string"&&(d="not ",c.substr(0,d.length)===d)?(h="must not be",c=c.replace(/^not /,"")):h="must be",function(m,g,_){return(_===void 0||_>m.length)&&(_=m.length),m.substring(_-g.length,_)===g}(l," argument"))f="The ".concat(l," ").concat(h," ").concat(o(c,"type"));else{var p=function(m,g,_){return typeof _!="number"&&(_=0),!(_+g.length>m.length)&&m.indexOf(g,_)!==-1}(l,".")?"property":"argument";f='The "'.concat(l,'" ').concat(p," ").concat(h," ").concat(o(c,"type"))}return f+=". Received type ".concat(typeof u)},TypeError),a("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),a("ERR_METHOD_NOT_IMPLEMENTED",function(l){return"The "+l+" method is not implemented"}),a("ERR_STREAM_PREMATURE_CLOSE","Premature close"),a("ERR_STREAM_DESTROYED",function(l){return"Cannot call "+l+" after a stream was destroyed"}),a("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),a("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),a("ERR_STREAM_WRITE_AFTER_END","write after end"),a("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),a("ERR_UNKNOWN_ENCODING",function(l){return"Unknown encoding: "+l},TypeError),a("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),i.exports.codes=n},{}],56:[function(t,i,r){(function(n){(function(){var a=Object.keys||function(m){var g=[];for(var _ in m)g.push(_);return g};i.exports=d;var o=t("./_stream_readable"),l=t("./_stream_writable");t("inherits")(d,o);for(var c=a(l.prototype),u=0;u0)if(typeof B=="string"||pe.objectMode||Object.getPrototypeOf(B)===u.prototype||(B=function(ye){return u.from(ye)}(B)),te)pe.endEmitted?w(N,new T):L(N,pe,B,!0);else if(pe.ended)w(N,new b);else{if(pe.destroyed)return!1;pe.reading=!1,pe.decoder&&!Y?(B=pe.decoder.write(B),pe.objectMode||B.length!==0?L(N,pe,B,!1):z(N,pe)):L(N,pe,B,!1)}else te||(pe.reading=!1,z(N,pe));return!pe.ended&&(pe.lengthB.highWaterMark&&(B.highWaterMark=function(Y){return Y>=k?Y=k:(Y--,Y|=Y>>>1,Y|=Y>>>2,Y|=Y>>>4,Y|=Y>>>8,Y|=Y>>>16,Y++),Y}(N)),N<=B.length?N:B.ended?B.length:(B.needReadable=!0,0))}function H(N){var B=N._readableState;d("emitReadable",B.needReadable,B.emittedReadable),B.needReadable=!1,B.emittedReadable||(d("emitReadable",B.flowing),B.emittedReadable=!0,n.nextTick(j,N))}function j(N){var B=N._readableState;d("emitReadable_",B.destroyed,B.length,B.ended),B.destroyed||!B.length&&!B.ended||(N.emit("readable"),B.emittedReadable=!1),B.needReadable=!B.flowing&&!B.ended&&B.length<=B.highWaterMark,q(N)}function z(N,B){B.readingMore||(B.readingMore=!0,n.nextTick(K,N,B))}function K(N,B){for(;!B.reading&&!B.ended&&(B.length0,B.resumeScheduled&&!B.paused?B.flowing=!0:N.listenerCount("data")>0&&N.resume()}function W(N){d("readable nexttick read 0"),N.read(0)}function Z(N,B){d("resume",B.reading),B.reading||N.read(0),B.resumeScheduled=!1,N.emit("resume"),q(N),B.flowing&&!B.reading&&N.read(0)}function q(N){var B=N._readableState;for(d("flow",B.flowing);B.flowing&&N.read()!==null;);}function ie(N,B){return B.length===0?null:(B.objectMode?Y=B.buffer.shift():!N||N>=B.length?(Y=B.decoder?B.buffer.join(""):B.buffer.length===1?B.buffer.first():B.buffer.concat(B.length),B.buffer.clear()):Y=B.buffer.consume(N,B.decoder),Y);var Y}function ae(N){var B=N._readableState;d("endReadable",B.endEmitted),B.endEmitted||(B.ended=!0,n.nextTick(ue,B,N))}function ue(N,B){if(d("endReadableNT",N.endEmitted,N.length),!N.endEmitted&&N.length===0&&(N.endEmitted=!0,B.readable=!1,B.emit("end"),N.autoDestroy)){var Y=B._writableState;(!Y||Y.autoDestroy&&Y.finished)&&B.destroy()}}function ce(N,B){for(var Y=0,te=N.length;Y=B.highWaterMark:B.length>0)||B.ended))return d("read: emitReadable",B.length,B.ended),B.length===0&&B.ended?ae(this):H(this),null;if((N=V(N,B))===0&&B.ended)return B.length===0&&ae(this),null;var te,oe=B.needReadable;return d("need readable",oe),(B.length===0||B.length-N0?ie(N,B):null)===null?(B.needReadable=B.length<=B.highWaterMark,N=0):(B.length-=N,B.awaitDrain=0),B.length===0&&(B.ended||(B.needReadable=!0),Y!==N&&B.ended&&ae(this)),te!==null&&this.emit("data",te),te},R.prototype._read=function(N){w(this,new C("_read()"))},R.prototype.pipe=function(N,B){var Y=this,te=this._readableState;switch(te.pipesCount){case 0:te.pipes=N;break;case 1:te.pipes=[te.pipes,N];break;default:te.pipes.push(N)}te.pipesCount+=1,d("pipe count=%d opts=%j",te.pipesCount,B);var oe=(!B||B.end!==!1)&&N!==n.stdout&&N!==n.stderr?pe:Et;function ne(ft,Tt){d("onunpipe"),ft===Y&&Tt&&Tt.hasUnpiped===!1&&(Tt.hasUnpiped=!0,d("cleanup"),N.removeListener("close",nt),N.removeListener("finish",Ke),N.removeListener("drain",ye),N.removeListener("error",Ve),N.removeListener("unpipe",ne),Y.removeListener("end",pe),Y.removeListener("end",Et),Y.removeListener("data",Ne),Ie=!0,!te.awaitDrain||N._writableState&&!N._writableState.needDrain||ye())}function pe(){d("onend"),N.end()}te.endEmitted?n.nextTick(oe):Y.once("end",oe),N.on("unpipe",ne);var ye=function(ft){return function(){var Tt=ft._readableState;d("pipeOnDrain",Tt.awaitDrain),Tt.awaitDrain&&Tt.awaitDrain--,Tt.awaitDrain===0&&l(ft,"data")&&(Tt.flowing=!0,q(ft))}}(Y);N.on("drain",ye);var Ie=!1;function Ne(ft){d("ondata");var Tt=N.write(ft);d("dest.write",Tt),Tt===!1&&((te.pipesCount===1&&te.pipes===N||te.pipesCount>1&&ce(te.pipes,N)!==-1)&&!Ie&&(d("false write response, pause",te.awaitDrain),te.awaitDrain++),Y.pause())}function Ve(ft){d("onerror",ft),Et(),N.removeListener("error",Ve),l(N,"error")===0&&w(N,ft)}function nt(){N.removeListener("finish",Ke),Et()}function Ke(){d("onfinish"),N.removeListener("close",nt),Et()}function Et(){d("unpipe"),Y.unpipe(N)}return Y.on("data",Ne),function(ft,Tt,Zt){if(typeof ft.prependListener=="function")return ft.prependListener(Tt,Zt);ft._events&&ft._events[Tt]?Array.isArray(ft._events[Tt])?ft._events[Tt].unshift(Zt):ft._events[Tt]=[Zt,ft._events[Tt]]:ft.on(Tt,Zt)}(N,"error",Ve),N.once("close",nt),N.once("finish",Ke),N.emit("pipe",Y),te.flowing||(d("pipe resume"),Y.resume()),N},R.prototype.unpipe=function(N){var B=this._readableState,Y={hasUnpiped:!1};if(B.pipesCount===0)return this;if(B.pipesCount===1)return N&&N!==B.pipes?this:(N||(N=B.pipes),B.pipes=null,B.pipesCount=0,B.flowing=!1,N&&N.emit("unpipe",this,Y),this);if(!N){var te=B.pipes,oe=B.pipesCount;B.pipes=null,B.pipesCount=0,B.flowing=!1;for(var ne=0;ne0,te.flowing!==!1&&this.resume()):N==="readable"&&(te.endEmitted||te.readableListening||(te.readableListening=te.needReadable=!0,te.flowing=!1,te.emittedReadable=!1,d("on readable",te.length,te.reading),te.length?H(this):te.reading||n.nextTick(W,this))),Y},R.prototype.addListener=R.prototype.on,R.prototype.removeListener=function(N,B){var Y=c.prototype.removeListener.call(this,N,B);return N==="readable"&&n.nextTick(U,this),Y},R.prototype.removeAllListeners=function(N){var B=c.prototype.removeAllListeners.apply(this,arguments);return N!=="readable"&&N!==void 0||n.nextTick(U,this),B},R.prototype.resume=function(){var N=this._readableState;return N.flowing||(d("resume"),N.flowing=!N.readableListening,function(B,Y){Y.resumeScheduled||(Y.resumeScheduled=!0,n.nextTick(Z,B,Y))}(this,N)),N.paused=!1,this},R.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},R.prototype.wrap=function(N){var B=this,Y=this._readableState,te=!1;for(var oe in N.on("end",function(){if(d("wrapped end"),Y.decoder&&!Y.ended){var pe=Y.decoder.end();pe&&pe.length&&B.push(pe)}B.push(null)}),N.on("data",function(pe){d("wrapped data"),Y.decoder&&(pe=Y.decoder.write(pe)),(!Y.objectMode||pe!=null)&&(Y.objectMode||pe&&pe.length)&&(B.push(pe)||(te=!0,N.pause()))}),N)this[oe]===void 0&&typeof N[oe]=="function"&&(this[oe]=function(pe){return function(){return N[pe].apply(N,arguments)}}(oe));for(var ne=0;ne-1))throw new T(z);return this._writableState.defaultEncoding=z,this},Object.defineProperty(R.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(R.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),R.prototype._write=function(z,K,U){U(new y("_write()"))},R.prototype._writev=null,R.prototype.end=function(z,K,U){var W=this._writableState;return typeof z=="function"?(U=z,z=null,K=null):typeof K=="function"&&(U=K,K=null),z!=null&&this.write(z,K),W.corked&&(W.corked=1,this.uncork()),W.ending||function(Z,q,ie){q.ending=!0,j(Z,q),ie&&(q.finished?n.nextTick(ie):Z.once("finish",ie)),q.ended=!0,Z.writable=!1}(this,W,U),this},Object.defineProperty(R.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(R.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(z){this._writableState&&(this._writableState.destroyed=z)}}),R.prototype.destroy=p.destroy,R.prototype._undestroy=p.undestroy,R.prototype._destroy=function(z,K){K(z)}}).call(this)}).call(this,t("_process"),typeof Xt<"u"?Xt:typeof self<"u"?self:typeof window<"u"?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(t,i,r){(function(n){(function(){var a;function o(x,A,b){return A in x?Object.defineProperty(x,A,{value:b,enumerable:!0,configurable:!0,writable:!0}):x[A]=b,x}var l=t("./end-of-stream"),c=Symbol("lastResolve"),u=Symbol("lastReject"),h=Symbol("error"),d=Symbol("ended"),f=Symbol("lastPromise"),p=Symbol("handlePromise"),m=Symbol("stream");function g(x,A){return{value:x,done:A}}function _(x){var A=x[c];if(A!==null){var b=x[m].read();b!==null&&(x[f]=null,x[c]=null,x[u]=null,A(g(b,!1)))}}var y=Object.getPrototypeOf(function(){}),v=Object.setPrototypeOf((o(a={get stream(){return this[m]},next:function(){var x=this,A=this[h];if(A!==null)return Promise.reject(A);if(this[d])return Promise.resolve(g(void 0,!0));if(this[m].destroyed)return new Promise(function(w,P){n.nextTick(function(){x[h]?P(x[h]):w(g(void 0,!0))})});var b,C=this[f];if(C)b=new Promise(function(w,P){return function(M,R){w.then(function(){P[d]?M(g(void 0,!0)):P[p](M,R)},R)}}(C,this));else{var T=this[m].read();if(T!==null)return Promise.resolve(g(T,!1));b=new Promise(this[p])}return this[f]=b,b}},Symbol.asyncIterator,function(){return this}),o(a,"return",function(){var x=this;return new Promise(function(A,b){x[m].destroy(null,function(C){C?b(C):A(g(void 0,!0))})})}),a),y);i.exports=function(x){var A,b=Object.create(v,(o(A={},m,{value:x,writable:!0}),o(A,c,{value:null,writable:!0}),o(A,u,{value:null,writable:!0}),o(A,h,{value:null,writable:!0}),o(A,d,{value:x._readableState.endEmitted,writable:!0}),o(A,p,{value:function(C,T){var w=b[m].read();w?(b[f]=null,b[c]=null,b[u]=null,C(g(w,!1))):(b[c]=C,b[u]=T)},writable:!0}),A));return b[f]=null,l(x,function(C){if(C&&C.code!=="ERR_STREAM_PREMATURE_CLOSE"){var T=b[u];return T!==null&&(b[f]=null,b[c]=null,b[u]=null,T(C)),void(b[h]=C)}var w=b[c];w!==null&&(b[f]=null,b[c]=null,b[u]=null,w(g(void 0,!0))),b[d]=!0}),x.on("readable",(function(C){n.nextTick(_,C)}).bind(null,b)),b}}).call(this)}).call(this,t("_process"))},{"./end-of-stream":64,_process:50}],62:[function(t,i,r){function n(h,d){var f=Object.keys(h);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(h);d&&(p=p.filter(function(m){return Object.getOwnPropertyDescriptor(h,m).enumerable})),f.push.apply(f,p)}return f}function a(h,d,f){return d in h?Object.defineProperty(h,d,{value:f,enumerable:!0,configurable:!0,writable:!0}):h[d]=f,h}function o(h,d){for(var f=0;f0?this.tail.next=m:this.head=m,this.tail=m,++this.length}},{key:"unshift",value:function(p){var m={data:p,next:this.head};this.length===0&&(this.tail=m),this.head=m,++this.length}},{key:"shift",value:function(){if(this.length!==0){var p=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,p}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(p){if(this.length===0)return"";for(var m=this.head,g=""+m.data;m=m.next;)g+=p+m.data;return g}},{key:"concat",value:function(p){if(this.length===0)return l.alloc(0);for(var m,g,_,y=l.allocUnsafe(p>>>0),v=this.head,x=0;v;)m=v.data,g=y,_=x,l.prototype.copy.call(m,g,_),x+=v.data.length,v=v.next;return y}},{key:"consume",value:function(p,m){var g;return py.length?y.length:p;if(v===y.length?_+=y:_+=y.slice(0,p),(p-=v)===0){v===y.length?(++g,m.next?this.head=m.next:this.head=this.tail=null):(this.head=m,m.data=y.slice(v));break}++g}return this.length-=g,_}},{key:"_getBuffer",value:function(p){var m=l.allocUnsafe(p),g=this.head,_=1;for(g.data.copy(m),p-=g.data.length;g=g.next;){var y=g.data,v=p>y.length?y.length:p;if(y.copy(m,m.length-p,0,v),(p-=v)===0){v===y.length?(++_,g.next?this.head=g.next:this.head=this.tail=null):(this.head=g,g.data=y.slice(v));break}++_}return this.length-=_,m}},{key:u,value:function(p,m){return c(this,function(g){for(var _=1;_0,function(A){m||(m=A),A&&_.forEach(u),x||(_.forEach(u),g(m))})});return f.reduce(h)}},{"../../../errors":55,"./end-of-stream":64}],67:[function(t,i,r){var n=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;i.exports={getHighWaterMark:function(a,o,l,c){var u=function(h,d,f){return h.highWaterMark!=null?h.highWaterMark:d?h[f]:null}(o,c,l);if(u!=null){if(!isFinite(u)||Math.floor(u)!==u||u<0)throw new n(c?l:"highWaterMark",u);return Math.floor(u)}return a.objectMode?16:16384}}},{"../../../errors":55}],68:[function(t,i,r){i.exports=t("events").EventEmitter},{events:22}],69:[function(t,i,r){(r=i.exports=t("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=t("./lib/_stream_writable.js"),r.Duplex=t("./lib/_stream_duplex.js"),r.Transform=t("./lib/_stream_transform.js"),r.PassThrough=t("./lib/_stream_passthrough.js"),r.finished=t("./lib/internal/streams/end-of-stream.js"),r.pipeline=t("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(t,i,r){i.exports=function(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("interval needed");var n;if(arguments.length>0){n=new Array(arguments.length-2);for(var a=0;a>5==6?2:g>>4==14?3:g>>3==30?4:g>>6==2?-1:-2}function c(g){var _=this.lastTotal-this.lastNeed,y=function(v,x,A){if((192&x[0])!=128)return v.lastNeed=0,"�";if(v.lastNeed>1&&x.length>1){if((192&x[1])!=128)return v.lastNeed=1,"�";if(v.lastNeed>2&&x.length>2&&(192&x[2])!=128)return v.lastNeed=2,"�"}}(this,g);return y!==void 0?y:this.lastNeed<=g.length?(g.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(g.copy(this.lastChar,_,0,g.length),void(this.lastNeed-=g.length))}function u(g,_){if((g.length-_)%2==0){var y=g.toString("utf16le",_);if(y){var v=y.charCodeAt(y.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=g[g.length-2],this.lastChar[1]=g[g.length-1],y.slice(0,-1)}return y}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=g[g.length-1],g.toString("utf16le",_,g.length-1)}function h(g){var _=g&&g.length?this.write(g):"";if(this.lastNeed){var y=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,y)}return _}function d(g,_){var y=(g.length-_)%3;return y===0?g.toString("base64",_):(this.lastNeed=3-y,this.lastTotal=3,y===1?this.lastChar[0]=g[g.length-1]:(this.lastChar[0]=g[g.length-2],this.lastChar[1]=g[g.length-1]),g.toString("base64",_,g.length-y))}function f(g){var _=g&&g.length?this.write(g):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function p(g){return g.toString(this.encoding)}function m(g){return g&&g.length?this.write(g):""}r.StringDecoder=o,o.prototype.write=function(g){if(g.length===0)return"";var _,y;if(this.lastNeed){if((_=this.fillLast(g))===void 0)return"";y=this.lastNeed,this.lastNeed=0}else y=0;return y=0?(T>0&&(x.lastNeed=T-1),T):--C=0?(T>0&&(x.lastNeed=T-2),T):--C=0?(T>0&&(T===2?T=0:x.lastNeed=T-3),T):0}(this,g,_);if(!this.lastNeed)return g.toString("utf8",_);this.lastTotal=y;var v=g.length-(y-this.lastNeed);return g.copy(this.lastChar,0,v),g.toString("utf8",_,v)},o.prototype.fillLast=function(g){if(this.lastNeed<=g.length)return g.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);g.copy(this.lastChar,this.lastTotal-this.lastNeed,0,g.length),this.lastNeed-=g.length}},{"safe-buffer":73}],76:[function(t,i,r){var n=t("punycode"),a=t("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=A,r.resolve=function(b,C){return A(b,!1,!0).resolve(C)},r.resolveObject=function(b,C){return b?A(b,!1,!0).resolveObject(C):C},r.format=function(b){return a.isString(b)&&(b=A(b)),b instanceof o?b.format():o.prototype.format.call(b)},r.Url=o;var l=/^([a-z0-9.+-]+:)/i,c=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,h=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r",` `," "]),d=["'"].concat(h),f=["%","/","?",";","#"].concat(d),p=["/","?","#"],m=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,_={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},x=t("querystring");function A(b,C,T){if(b&&a.isObject(b)&&b instanceof o)return b;var w=new o;return w.parse(b,C,T),w}o.prototype.parse=function(b,C,T){if(!a.isString(b))throw new TypeError("Parameter 'url' must be a string, not "+typeof b);var w=b.indexOf("?"),P=w!==-1&&w127?ae+="x":ae+=ie[ue];if(!ae.match(m)){var N=Z.slice(0,K),B=Z.slice(K+1),Y=ie.match(g);Y&&(N.push(Y[1]),B.unshift(Y[2])),B.length&&(R="/"+B.join(".")+R),this.hostname=N.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),W||(this.hostname=n.toASCII(this.hostname));var te=this.port?":"+this.port:"",oe=this.hostname||"";this.host=oe+te,this.href+=this.host,W&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),R[0]!=="/"&&(R="/"+R))}if(!_[k])for(K=0,q=d.length;K0)&&T.host.split("@"))&&(T.auth=Y.shift(),T.host=T.hostname=Y.shift())),T.search=b.search,T.query=b.query,a.isNull(T.pathname)&&a.isNull(T.search)||(T.path=(T.pathname?T.pathname:"")+(T.search?T.search:"")),T.href=T.format(),T;if(!ie.length)return T.pathname=null,T.search?T.path="/"+T.search:T.path=null,T.href=T.format(),T;for(var ue=ie.slice(-1)[0],ce=(T.host||b.host||ie.length>1)&&(ue==="."||ue==="..")||ue==="",N=0,B=ie.length;B>=0;B--)(ue=ie[B])==="."?ie.splice(B,1):ue===".."?(ie.splice(B,1),N++):N&&(ie.splice(B,1),N--);if(!Z&&!q)for(;N--;N)ie.unshift("..");!Z||ie[0]===""||ie[0]&&ie[0].charAt(0)==="/"||ie.unshift(""),ce&&ie.join("/").substr(-1)!=="/"&&ie.push("");var Y,te=ie[0]===""||ie[0]&&ie[0].charAt(0)==="/";return ae&&(T.hostname=T.host=te?"":ie.length?ie.shift():"",(Y=!!(T.host&&T.host.indexOf("@")>0)&&T.host.split("@"))&&(T.auth=Y.shift(),T.host=T.hostname=Y.shift())),(Z=Z||T.host&&ie.length)&&!te&&ie.unshift(""),ie.length?T.pathname=ie.join("/"):(T.pathname=null,T.path=null),a.isNull(T.pathname)&&a.isNull(T.search)||(T.path=(T.pathname?T.pathname:"")+(T.search?T.search:"")),T.auth=b.auth||T.auth,T.slashes=T.slashes||b.slashes,T.href=T.format(),T},o.prototype.parseHost=function(){var b=this.host,C=c.exec(b);C&&((C=C[0])!==":"&&(this.port=C.substr(1)),b=b.substr(0,b.length-C.length)),b&&(this.hostname=b)}},{"./util":77,punycode:51,querystring:54}],77:[function(t,i,r){i.exports={isString:function(n){return typeof n=="string"},isObject:function(n){return typeof n=="object"&&n!==null},isNull:function(n){return n===null},isNullOrUndefined:function(n){return n==null}}},{}],78:[function(t,i,r){(function(n){(function(){function a(o){try{if(!n.localStorage)return!1}catch{return!1}var l=n.localStorage[o];return l!=null&&String(l).toLowerCase()==="true"}i.exports=function(o,l){if(a("noDeprecation"))return o;var c=!1;return function(){if(!c){if(a("throwDeprecation"))throw new Error(l);a("traceDeprecation")?console.trace(l):console.warn(l),c=!0}return o.apply(this,arguments)}}}).call(this)}).call(this,typeof Xt<"u"?Xt:typeof self<"u"?self:typeof window<"u"?window:{})},{}],79:[function(t,i,r){i.exports=function n(a,o){if(a&&o)return n(a)(o);if(typeof a!="function")throw new TypeError("need wrapper function");return Object.keys(a).forEach(function(c){l[c]=a[c]}),l;function l(){for(var c=new Array(arguments.length),u=0;u0)for(var d=0,f=arguments.length;d1)d=h;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");f=this.head.next,d=this.head.value}for(var p=0;f!==null;p++)d=u(d,f.value,p),f=f.next;return d},n.prototype.reduceReverse=function(u,h){var d,f=this.tail;if(arguments.length>1)d=h;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");f=this.tail.prev,d=this.tail.value}for(var p=this.length-1;f!==null;p--)d=u(d,f.value,p),f=f.prev;return d},n.prototype.toArray=function(){for(var u=new Array(this.length),h=0,d=this.head;d!==null;h++)u[h]=d.value,d=d.next;return u},n.prototype.toArrayReverse=function(){for(var u=new Array(this.length),h=0,d=this.tail;d!==null;h++)u[h]=d.value,d=d.prev;return u},n.prototype.slice=function(u,h){(h=h||this.length)<0&&(h+=this.length),(u=u||0)<0&&(u+=this.length);var d=new n;if(hthis.length&&(h=this.length);for(var f=0,p=this.head;p!==null&&fthis.length&&(h=this.length);for(var f=this.length,p=this.tail;p!==null&&f>h;f--)p=p.prev;for(;p!==null&&f>u;f--,p=p.prev)d.push(p.value);return d},n.prototype.splice=function(u,h,...d){u>this.length&&(u=this.length-1),u<0&&(u=this.length+u);for(var f=0,p=this.head;p!==null&&f'},info:{color:"#0052d9",icon:''},warning:{color:"#e37318",icon:''},error:{color:"#d54941",icon:''},question:{color:"#0052d9",icon:''}},wf={};class W0t{constructor(e,t){ke(this,"box");ke(this,"icon");ke(this,"text");ke(this,"closeBtn");ke(this,"duration");ke(this,"content");ke(this,"theme");ke(this,"placement");ke(this,"id");this.parentElement=e,this.box=document.createElement("div"),this.icon=document.createElement("div"),this.text=document.createElement("div"),this.box.className="meta2d-message",this.icon.className="icon",this.text.className="text",this.icon.innerHTML=CEe[t.theme||"info"].icon,this.text.innerHTML=t.content,this.box.appendChild(this.icon),this.box.appendChild(this.text),t.closeBtn&&(this.closeBtn=document.createElement("div"),this.closeBtn.className="close",this.closeBtn.innerHTML="x",this.closeBtn.onclick=()=>{this.close()},this.box.appendChild(this.closeBtn)),e.appendChild(this.box);let i;for(let r=0;r{this.close()},this.duration);let e=-1;Object.keys(wf).forEach(t=>{var i;((i=wf[t])==null?void 0:i.placement)===this.placement&&e++}),this.setPosition(this.placement,e),this.icon.children[0].style.fill=CEe[this.theme].color}setPosition(e,t=0){switch(e){case"top":this.box.style.top=`${30+t*60}px`,this.box.style.left="50%";break;case"bottom":this.box.style.bottom=`${30+t*60}px`,this.box.style.left="50%";break;case"left":this.box.style.top=`${30+t*60}px`,this.box.style.left="30px";break;case"right":this.box.style.top=`${30+t*60}px`,this.box.style.right="30px";break}}close(){Object.keys(wf).forEach(e=>{var t;if(((t=wf[e])==null?void 0:t.placement)===this.placement)switch(this.placement){case"top":case"left":case"right":wf[e].box.style.top=parseInt(wf[e].box.style.top)-60+"px";break;case"bottom":wf[e].box.style.bottom=parseInt(wf[e].box.style.bottom)-60+"px";break}}),wf[this.id]=null,delete wf[this.id],this.box.remove()}}function K0t(s,e){s.jetLinksList.length&&(s.jetLinksClient=new WebSocket(`${e.url}/${localStorage.getItem("X-Access-Token")||Y$("X-Access-Token")||new URLSearchParams(location.search).get("X-Access-Token")||""}`),s.jetLinksClient.onmessage=t=>{var r;const i=JSON.parse(t.data);if(i.payload&&((r=i.payload)!=null&&r.properties)){const n=[];for(let a in i.payload.properties)a.startsWith("_")||n.push({id:`${i.payload.headers.productId}#${i.payload.deviceId}#${a}`,value:i.payload.properties[a]});s.setDatas(n,{history:!1})}},s.jetLinksClient.onopen=()=>{s.jetLinksList.forEach(t=>{s.jetLinksClient.send(JSON.stringify({type:"sub",topic:`/device${t.topic}/message/property/report`,parameter:{deviceId:t.deviceId,properties:t.properties,history:1},id:t.topic+"-"+fs()}))})})}function H0t(s){s.jetLinksClient&&(s.jetLinksClient.close(),s.jetLinksClient=void 0)}function j0t(s,e,t){const i=[];return t.list.forEach((r,n)=>{var o,l;const a=r.params?s.findOne(r.params):e;i[n]={deviceId:a.deviceId,productId:a.productId,properties:{}};for(let c in r.value)if(r.value[c]===void 0||r.value[c]===""){const u=(o=a.realTimes)==null?void 0:o.find(h=>h.propertyId===c);u&&(i[n].properties[c]=a[u.key])}else if(typeof r.value[c]=="string"&&((l=r.value[c])==null?void 0:l.indexOf("${"))>-1){let u=r.value[c].match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));u!=null&&u.length&&(i[n].properties[c]=a[u[0]]??s.getDynamicParam(u[0]))}else i[n].properties[c]=r.value[c]}),i}async function X0t(s,e){e.forEach(async t=>{(await fetch(`/api/device-instance/${t.deviceId}/property`,{headers:{"X-Access-Token":localStorage.getItem("X-Access-Token")||new URLSearchParams(location.search).get("X-Access-Token")||"","Content-Type":"application/json"},method:"put",body:JSON.stringify(t.properties)})).ok?(console.info("发送成功"),s.message({theme:"success",content:"下发成功"})):s.message({theme:"error",content:"下发失败"})})}class oFe{constructor(e,t={}){ke(this,"store");ke(this,"canvas");ke(this,"websocket");ke(this,"mqttClient");ke(this,"websockets");ke(this,"mqttClients");ke(this,"penPluginMap",new Map);ke(this,"socketFn");ke(this,"events",{});ke(this,"map");ke(this,"mapTimer");ke(this,"facePen",$P);ke(this,"getWords",SNe);ke(this,"calcTextLines",iz);ke(this,"calcTextRect",L1);ke(this,"calcTextDrawRect",CNe);ke(this,"jetLinksList",[]);ke(this,"jetLinksClient");ke(this,"register",R1);ke(this,"registerCanvasDraw",_5);ke(this,"registerAnchors",$ce);ke(this,"websocketTimes",0);ke(this,"mqttTimes",0);ke(this,"httpTimer");ke(this,"httpTimerList",[]);ke(this,"updateTimer");ke(this,"updateTimerList",[]);ke(this,"sqlTimerList",[]);ke(this,"onEvent",(e,t)=>{switch(e){case"add":t.forEach(i=>{var r;(r=i.onAdd)==null||r.call(i,i)}),this.onSizeUpdate();break;case"enter":t&&t.onMouseEnter&&t.onMouseEnter(t,this.canvas.mousePos),this.store.data.locked&&this.doEvent(t,e);break;case"leave":t&&t.onMouseLeave&&t.onMouseLeave(t,this.canvas.mousePos),this.store.data.locked&&this.doEvent(t,e);break;case"active":case"inactive":this.store.data.locked&&t.forEach(i=>{this.doEvent(i,e)});break;case"click":if(this.store.data.locked&&t.pen&&!t.pen.disabled&&t.pen.switch&&(t.pen.checked=!t.pen.checked,t.pen.calculative.checked=t.pen.checked,t.pen.calculative.gradient=void 0,t.pen.calculative.radialGradient=void 0),t.pen&&t.pen.formId){const i=this.store.pens[t.pen.formId];t.pen.formType==="submit"?this.store.data.locked&&i&&!i.disabled&&this.doEvent(i,"submit"):t.pen.formType==="reset"&&(I0t(t.pen),this.store.data.locked&&i&&!i.disabled&&this.doEvent(i,"reset"))}t.pen&&t.pen.onClick&&!t.pen.disabled&&t.pen.onClick(t.pen,this.canvas.mousePos),this.store.data.locked&&t.pen&&!t.pen.disabled&&this.doEvent(t.pen,e);break;case"contextmenu":t.pen&&t.pen.onContextmenu&&!t.pen.disabled&&t.pen.onContextmenu(t.pen,this.canvas.mousePos),this.store.data.locked&&t.pen&&!t.pen.disabled&&this.doEvent(t.pen,e);break;case"mousedown":t.pen&&t.pen.onMouseDown&&!t.pen.disabled&&t.pen.onMouseDown(t.pen,this.canvas.mousePos),this.store.data.locked&&t.pen&&!t.pen.disabled&&this.doEvent(t.pen,e);break;case"mouseup":t.pen&&t.pen.onMouseUp&&!t.pen.disabled&&t.pen.onMouseUp(t.pen,this.canvas.mousePos),this.store.data.locked&&t.pen&&!t.pen.disabled&&this.doEvent(t.pen,e);break;case"dblclick":this.store.data.locked&&t.pen&&!t.pen.disabled&&this.doEvent(t.pen,e);break;case"valueUpdate":t&&AEe(t,t.formValue),this.store.data.locked&&this.doEvent(t,e),this.canvas.tooltip.updateText(t);break;case"update":case"delete":case"translatePens":case"rotatePens":case"resizePens":this.onSizeUpdate();break;case"navigator":this.store.data.id||console.warn("请先保存当前图纸"),this.navigatorTo(t.params);break;case"input":this.store.data.locked&&t&&!t.disabled&&this.doEvent(t,e);break;case"change":t.pen&&AEe(t.pen),this.store.data.locked&&t&&!t.disabled&&this.doEvent(t,e);break}this.doMessageEvent(e)});ke(this,"doEvent",(e,t)=>{var n,a,o,l,c,u,h,d,f,p;if(!e)return;let i=!1,r=[];if((n=e.events)==null||n.forEach((m,g)=>{var _;if(m.actions&&m.actions.length){if(m.name===t){let y=!1;m.conditions&&m.conditions.length?m.conditionType==="and"?y=m.conditions.every(v=>this.judgeCondition(e,v.key,v)):m.conditionType==="or"&&(y=m.conditions.some(v=>this.judgeCondition(e,v.key,v))):y=!0,y&&r.push(g)}}else if(i=!0,this.events[m.action]&&m.name===t){let y=!((_=m.where)!=null&&_.type);if(m.where){const{fn:v,fnJs:x,comparison:A,key:b,value:C}=m.where;if(v)y=v(e,{meta2d:this});else if(x){try{m.where.fn=new Function("pen","context",x)}catch(T){console.error("Error: make function:",T)}m.where.fn&&(y=m.where.fn(e,{meta2d:this}))}else{let T=e[b];switch(["x","y","width","height"].includes(b)&&(T=this.getPenRect(e)[b]),A){case">":y=T>+C;break;case">=":y=T>=+C;break;case"<":y=T<+C;break;case"<=":y=T<=+C;break;case"=":case"==":y=T==C;break;case"!=":y=T!=C;break;case"[)":y=II(+T,C);break;case"![)":y=!II(+T,C);break;case"[]":y=PI(T,C);break;case"![]":y=!PI(T,C);break}}}y&&r.push(g)}}),i?(a=e.events)==null||a.forEach((m,g)=>{r.includes(g)&&this.events[m.action](e,m)}):(o=e.events)==null||o.forEach(async(m,g)=>{if(r.includes(g)){if(m.confirm&&!await this.canvas.popconfirm.showModal(e,this.canvas.mousePos,m.confirmTitle))return;m.actions.forEach(_=>{if(_.timeout){let y=setTimeout(()=>{this.events[_.action]&&(this.events[_.action](e,_),clearTimeout(y),y=null)},_.timeout)}else this.events[_.action]&&this.events[_.action](e,_)})}}),t==="valueUpdate"){(l=e.realTimes)==null||l.forEach(g=>{var y,v;let _=[];(y=g.triggers)==null||y.forEach((x,A)=>{var C;let b=!1;(C=x.conditions)!=null&&C.length?x.conditionType==="and"?b=x.conditions.every(T=>this.judgeCondition(e,g.key,T)):x.conditionType==="or"&&(b=x.conditions.some(T=>this.judgeCondition(e,g.key,T))):b=!0,b&&_.push(A)}),(v=g.triggers)==null||v.forEach((x,A)=>{var b;_.includes(A)&&((b=x.actions)==null||b.forEach(C=>{if(C.timeout){let T=setTimeout(()=>{this.events[C.action]&&(this.events[C.action](e,C),clearTimeout(T),T=null)},C.timeout)}else this.events[C.action](e,C)}))})});let m=[];if((c=this.store.globalTriggers[e.id])==null||c.forEach((g,_)=>{var v;let y=!1;(v=g.conditions)!=null&&v.length?g.conditionType==="and"?y=g.conditions.every(x=>this.judgeCondition(this.store.pens[x.source],x.key,x)):g.conditionType==="or"&&(y=g.conditions.some(x=>this.judgeCondition(this.store.pens[x.source],x.key,x))):y=!0,y&&m.push(_)}),(u=this.store.globalTriggers[e.id])==null||u.forEach((g,_)=>{var y;m.includes(_)&&((y=g.actions)==null||y.forEach(v=>{if(v.timeout){let x=setTimeout(()=>{this.events[v.action]&&(this.events[v.action](e,v),clearTimeout(x),x=null)},v.timeout)}else this.events[v.action](e,v)}))}),(h=e.triggers)!=null&&h.length){for(let g of e.triggers)if((d=g.status)!=null&&d.length)for(let _ of g.status){let y=!1;if((f=_.conditions)!=null&&f.length?_.conditionType==="and"?y=_.conditions.every(v=>this.judgeCondition(e,v.key,v)):_.conditionType==="or"&&(y=_.conditions.some(v=>this.judgeCondition(e,v.key,v))):y=!0,y){(p=_.actions)==null||p.forEach(v=>{if(v.timeout){let x=setTimeout(()=>{this.events[v.action]&&(this.events[v.action](e,v),clearTimeout(x),x=null)},v.timeout)}else this.events[v.action](e,v)});break}}}}this.doEvent(this.store.pens[e.parentId],t)});ke(this,"doDataEvent",e=>{var r,n,a;if(!((r=this.store.data.dataEvents)!=null&&r.length))return;const t=e.reduce((o,{dataId:l,id:c,value:u})=>(o[c||l]=u,o),{});let i=[];(n=this.store.data.dataEvents)==null||n.forEach((o,l)=>{let c=!1;o.conditions&&o.conditions.length?o.conditionType==="and"?c=o.conditions.every(u=>this.dataJudegeCondition(t,u.key,u)):o.conditionType==="or"&&(c=o.conditions.some(u=>this.dataJudegeCondition(t,u.key,u))):c=!0,c&&i.push(l)}),(a=this.store.data.dataEvents)==null||a.forEach((o,l)=>{var c;i.includes(l)&&((c=o.actions)==null||c.forEach(u=>{this.events[u.action](t,u)}))})});ke(this,"renderPenRaw",$$);ke(this,"setElemPosition",Ha);ke(this,"setLifeCycleFunc",lpt);this.store=gft(fs()),this.setOptions(t),this.setDatabyOptions(t),this.init(e),this.register(z0t()),this.registerCanvasDraw({cube:Vpt}),this.registerAnchors(V0t()),globalThis.meta2d=this,this.initEventFns(),this.store.emitter.on("*",this.onEvent)}get beforeAddPen(){return this.canvas.beforeAddPen}set beforeAddPen(e){this.canvas.beforeAddPen=e}get beforeAddPens(){return this.canvas.beforeAddPens}set beforeAddPens(e){this.canvas.beforeAddPens=e}get beforeAddAnchor(){return this.canvas.beforeAddAnchor}set beforeAddAnchor(e){this.canvas.beforeAddAnchor=e}get beforeRemovePens(){return this.canvas.beforeRemovePens}set beforeRemovePens(e){this.canvas.beforeRemovePens=e}get beforeRemoveAnchor(){return this.canvas.beforeRemoveAnchor}set beforeRemoveAnchor(e){this.canvas.beforeRemoveAnchor=e}setOptions(e={}){var t;(e.grid!==void 0||e.gridColor!==void 0||e.gridSize!==void 0)&&this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),(e.rule!==void 0||e.ruleColor!==void 0||e.ruleOptions!==void 0)&&(this.store.patchFlagsTop=!0,e.ruleOptions&&(t=this.store.options)!=null&&t.ruleOptions&&(Object.assign(this.store.options.ruleOptions,e.ruleOptions),e.ruleOptions=this.store.options.ruleOptions)),e.background!==void 0&&this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),e.resizeMode!==void 0&&(e.resizeMode||(this.canvas.hotkeyType=ia.None)),(e.width!==void 0||e.height!==void 0)&&(this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),this.canvas&&this.canvas.canvasTemplate.canvas.style.backgroundImage&&(this.canvas.canvasTemplate.canvas.style.backgroundImage="")),this.store.options=Object.assign(this.store.options,e),this.canvas&&e.scroll!==void 0&&(e.scroll?(!this.canvas.scroll&&(this.canvas.scroll=new iFe(this.canvas)),this.canvas.scroll.show()):this.canvas.scroll&&this.canvas.scroll.hide())}getOptions(){return this.store.options}setTheme(e){this.store.data.theme=e,this.setBackgroundColor(this.store.theme[e].background),this.canvas.parentElement.style.background=this.store.theme[e].parentBackground,this.store.data.color=this.store.theme[e].color,this.setOptions({ruleColor:this.store.theme[e].ruleColor,ruleOptions:this.store.theme[e].ruleOptions}),wse.updateCssRule(this.store.id,e),this.canvas.initGlobalStyle(),this.render()}setDatabyOptions(e={}){const{color:t,activeColor:i,activeBackground:r,grid:n,gridColor:a,gridSize:o,fromArrow:l,toArrow:c,rule:u,ruleColor:h,textColor:d,x:f=0,y:p=0}=e;this.setRule({rule:u,ruleColor:h}),this.setGrid({grid:n,gridColor:a,gridSize:o}),this.store.data=Object.assign(this.store.data,{textColor:d,color:t,activeColor:i,activeBackground:r,fromArrow:l,toArrow:c,x:f,y:p})}init(e){typeof e=="string"?this.canvas=new yEe(this,document.getElementById(e),this.store):this.canvas=new yEe(this,e,this.store),this.canvas.initGlobalStyle(),this.resize(),this.canvas.listen(),wse.createThemeSheet(this.store.data.theme,this.store.id)}initEventFns(){this.events[nc.Link]=(e,t)=>{if(window&&t.value&&typeof t.value=="string"){window.open(t.value,t.params??"_blank");return}console.warn("[meta2d] Link param is not a string")},this.events[nc.SetProps]=(e,t)=>{const i=t.value;if(i&&typeof i=="object"){(t.params?this.find(t.params):this.find(e.id)).forEach(n=>{i.hasOwnProperty("visible")&&n.visible!==i.visible&&this.setVisible(n,i.visible),this.setValue({id:n.id,...i},{render:!1,doEvent:!1})}),this.render();return}console.warn("[meta2d] SetProps value is not an object")},this.events[nc.StartAnimate]=(e,t)=>{let i=e;if(t.value&&(i=this.findOne(t.value)),!(this.store.animates.has(i)&&!i.calculative.pause&&i.animateName===t.params)){if(t.targetType&&t.params){this.startAnimate(t.value||[e],t.params);return}if(!t.value||typeof t.value=="string"){this.startAnimate(t.value||[e]);return}console.warn("[meta2d] StartAnimate value is not a string")}},this.events[nc.PauseAnimate]=(e,t)=>{if(!t.value||typeof t.value=="string"){this.pauseAnimate(t.value||[e]);return}console.warn("[meta2d] PauseAnimate value is not a string")},this.events[nc.StopAnimate]=(e,t)=>{if(!t.value||typeof t.value=="string"){if(t.value){let i=this.findOne(t.value);if(!this.store.animates.has(i))return}else if(!this.store.animates.has(e))return;this.stopAnimate(t.value||[e]);return}console.warn("[meta2d] StopAnimate event value is not a string")},this.events[nc.StartVideo]=(e,t)=>{if(!t.value||typeof t.value=="string"){this.startVideo(t.value||[e]);return}console.warn("[meta2d] StartVideo value is not a string")},this.events[nc.PauseVideo]=(e,t)=>{if(!t.value||typeof t.value=="string"){this.pauseVideo(t.value||[e]);return}console.warn("[meta2d] PauseVideo value is not a string")},this.events[nc.StopVideo]=(e,t)=>{if(!t.value||typeof t.value=="string"){this.stopVideo(t.value||[e]);return}console.warn("[meta2d] StopVideo event value is not a string")},this.events[nc.JS]=(e,t,i)=>{var r;if(t.value&&!t.fn)try{if(typeof t.value!="string")throw new Error("[meta2d] Function value must be string");const n=t.value;t.fn=new Function("pen","params","context",n)}catch(n){console.error("[meta2d]: Error on make a function:",n)}(r=t.fn)==null||r.call(t,e,i||t.params,{meta2d:this,eventName:t.name})},this.events[nc.GlobalFn]=(e,t)=>{if(typeof t.value!="string"){console.warn("[meta2d] GlobalFn value must be a string");return}globalThis[t.value]&&globalThis[t.value](e,t.params)},this.events[nc.Emit]=(e,t)=>{if(typeof t.value!="string"){console.warn("[meta2d] Emit value must be a string");return}this.store.emitter.emit(t.value,{pen:e,params:t.params,eventName:t.name})},this.events[nc.SendPropData]=(e,t)=>{const i=bt(t.value);if(i&&typeof i=="object"){const r=t.params?this.findOne(t.params):e;for(let n in i)(i[n]===void 0||i[n]==="")&&(i[n]=r[n]);i.id=r.id,this.doSendDataEvent(i,t.extend);return}console.warn("[meta2d] SendPropData value is not an object")},this.events[nc.SendVarData]=(e,t)=>{const i=bt(t.value);if(i&&typeof i=="object"){const r=t.params?this.findOne(t.params):e;let n=[];for(let a in i){let o={dataId:a,value:i[a]};if(!o.value){let l=r.form.find(c=>c.dataIds&&c.dataIds.dataId===o.dataId);l&&(o.value=r[l.key])}n.push(o)}this.doSendDataEvent(n,t.extend);return}console.warn("[meta2d] SendVarData value is not an object")},this.events[nc.Navigator]=(e,t)=>{t.value&&typeof t.value=="string"&&this.navigatorTo(t.value)},this.events[nc.Dialog]=(e,t)=>{var i;if(t.params&&typeof t.params=="string"){let r=t.params;if(t.params.includes("${")){let a=(i=t.params.match(/\$\{([^}]+)\}/g))==null?void 0:i.map(o=>o.slice(2,-1));a&&(a==null||a.forEach(o=>{r=r.replace(`\${${o}}`,e[o])}))}Object.keys(t.extend).forEach(a=>{["x","y","width","height"].includes(a)||(r.indexOf("?")!==-1?r+=`&${a}=${t.extend[a]}`:r+=`?${a}=${t.extend[a]}`)});const n=this.getEventData(t.list,e);this.canvas.dialog.show(t.value,r,t.extend,n)}},this.events[nc.SendData]=(e,t)=>{var r,n,a;if((r=t.list)!=null&&r.length){if(t.network&&t.network.protocol==="ADIIOT"){const l=j0t(this,e,t);l.length&&X0t(this,l);return}const o=this.getEventData(t.list,e);e.deviceId&&(o.deviceId=e.deviceId),e.formId&&e.formData&&Object.assign(o,e.formData),this.sendDataToNetWork(o,e,t);return}const i=bt(t.value);if(i&&typeof i=="object"&&t.targetType==="id"){const o=t.params?this.findOne(t.params):e;for(let l in i)if(i[l]===void 0||i[l]==="")i[l]=o[l];else if(typeof i[l]=="string"&&((n=i[l])==null?void 0:n.indexOf("${"))>-1){let c=(a=i[l].match(/\$\{([^}]+)\}/g))==null?void 0:a.map(u=>u.slice(2,-1));c!=null&&c.length&&(i[l]=o[c[0]]??this.getDynamicParam(c[0]))}o.deviceId&&(i.deviceId=o.deviceId),this.sendDataToNetWork(i,e,t);return}},this.events[nc.PostMessage]=(e,t)=>{if(typeof t.value!="string"){console.warn("[meta2d] Emit value must be a string");return}const i=t.params?this.findOne(t.params):e;if(i.name!=="iframe"||!i.iframe){console.warn("不是嵌入页面");return}let r=M5(i.iframe.split("?")[1]);const n=this.getEventData(t.list,i);i.calculative.singleton.div.children[0].contentWindow.postMessage(JSON.stringify({name:t.value,id:r.id,data:n}),"*")},this.events[nc.PostMessageToParent]=(e,t)=>{if(typeof t.value!="string"){console.warn("[meta2d] Emit value must be a string");return}const i=this.getEventData(t.list,e);window.parent.postMessage(JSON.stringify({name:t.value,data:i}),"*")},this.events[nc.Message]=(e,t)=>{this.message({theme:t.params,content:t.value,...t.extend})}}getEventData(e,t){const i={};return e!=null&&e.length&&e.forEach(r=>{var a,o;const n=r.params?this.findOne(r.params):t;for(let l in r.value)if(r.value[l]===void 0||r.value[l]==="")i[l]=n[l];else if(typeof r.value[l]=="string"&&((a=r.value[l])==null?void 0:a.indexOf("${"))>-1){let c=(o=r.value[l].match(/\$\{([^}]+)\}/g))==null?void 0:o.map(u=>u.slice(2,-1));c!=null&&c.length&&(i[l]=n[c[0]]??this.getDynamicParam(c[0]))}else i[l]=r.value[l]}),Object.keys(i).length?i:{}}message(e){new W0t(this.canvas.parentElement,e).init()}closeAll(){for(let e in wf)wf[e].close()}async navigatorTo(e){var r;if(!e)return;if((r=M5())==null?void 0:r.id){const n=new URL(window.location);n.searchParams.set("id",e),history.pushState({},"",n)}const i=await MNe(this.store,e);i&&(this.open(i),this.fitView(!0,10))}doSendDataEvent(e,t){let i=JSON.stringify(e);this.mqttClient&&this.mqttClient.connected&&(t?t.split(",").forEach(r=>{this.mqttClient.publish(r,i)}):this.store.data.mqttTopics&&this.store.data.mqttTopics.split(",").forEach(r=>{this.mqttClient.publish(r,i)})),this.websocket&&this.websocket.readyState===1&&this.websocket.send(i),(this.store.data.https||this.store.data.http)&&this.sendDatabyHttp(i),this.store.emitter.emit("sendData",i)}async sendDataToNetWork(e,t,i){var n,a,o,l,c;const r=bt(i.network);if(r.data&&(Object.assign(r,r.data),delete r.data),!!r.url){if(r.protocol==="http"){if(typeof r.headers=="object"){for(let f in r.headers)if(typeof r.headers[f]=="string"){let p=(n=r.headers[f].match(/\$\{([^}]+)\}/g))==null?void 0:n.map(m=>m.slice(2,-1));p&&(r.headers[f]=r.headers[f].replace(`\${${p[0]}}`,this.getDynamicParam(p[0])))}}let u,h=r.url;if(r.method==="GET"&&(u="?"+Object.keys(e).map(f=>f+"="+e[f]).join("&")),r.method==="POST"&&h.indexOf("${")>-1){let f=(a=h.match(/\$\{([^}]+)\}/g))==null?void 0:a.map(p=>p.slice(2,-1));f&&f.forEach(p=>{h=h.replace(`\${${p}}`,oS(t,p)||this.getDynamicParam(p))})}const d=await fetch(h+(u||""),{headers:r.headers||{},method:r.method,body:r.method==="POST"?JSON.stringify(e):void 0});if(d.ok){if(i.callback){const f=await d.text();if(!i.fn)try{if(typeof i.callback!="string")throw new Error("[meta2d] Function callback must be string");const p=i.callback;i.fn=new Function("pen","data","context",p)}catch(p){console.error("[meta2d]: Error on make a function:",p)}(o=i.fn)==null||o.call(i,t,f,{meta2d:this,e:i})}console.info("http消息发送成功")}}else if(r.protocol==="mqtt"){const u=(l=this.mqttClients)==null?void 0:l.filter(h=>h.options.href===r.url);if(u&&u.length)u[0].connected&&r.topics.split(",").forEach(h=>{u[0].publish(h,JSON.stringify(e))});else{let h=sY.connect(r.url,r.options);h.on("connect",()=>{console.info("mqtt连接成功"),r.topics.split(",").forEach(d=>{h.publish(d,JSON.stringify(e)),setTimeout(()=>{h==null||h.end()},1e3)})})}}else if(r.protocol==="websocket"){const u=(c=this.websockets)==null?void 0:c.filter(h=>h.url===r.url);if(u&&u.length)u[0].readyState===1&&u[0].send(JSON.stringify(e));else{let h=new WebSocket(r.url,r.protocols||void 0);h.onopen=function(){console.info("websocket连接成功"),h.send(JSON.stringify(e)),setTimeout(()=>{h.close()},100)}}}}}resize(e,t){this.canvas.resize(e,t),this.render(),this.store.emitter.emit("resize",{width:e,height:t}),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.init()}async addPen(e,t,i=!0,r=!1){return await this.canvas.addPen(e,t,i,r)}async addPens(e,t,i=!1){return await this.canvas.addPens(e,t,i)}render(e){var t;(t=this.canvas)==null||t.render(e)}async setBackgroundImage(e,t){var o,l,c,u;let i=this;async function r(h){return new Promise(d=>{const f=new Image;f.src=h,i.store.options.cdn&&!(h.startsWith("http")||h.startsWith("//")||h.startsWith("data:image"))&&(f.src=i.store.options.cdn+h),f.crossOrigin="anonymous",f.onload=()=>{d(f)}})}this.store.data.bkImage=e;const n=(t==null?void 0:t.width)||((o=this.store.data)==null?void 0:o.width)||((l=this.store.options)==null?void 0:l.width),a=(t==null?void 0:t.height)||((c=this.store.data)==null?void 0:c.height)||((u=this.store.options)==null?void 0:u.height);if(n&&a?(this.canvas.canvasTemplate.canvas.style.backgroundImage=null,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)):this.canvas.canvasTemplate.canvas.style.backgroundImage=e?`url('${e}')`:"",e){const h=await r(e);this.store.bkImg=h,n&&a&&this.canvas&&(this.canvas.canvasTemplate.init(),this.render())}else this.store.bkImg=null}setBackgroundColor(e=this.store.data.background){this.store.data.background=e,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)}setGrid({grid:e=this.store.data.grid,gridColor:t=this.store.data.gridColor,gridSize:i=this.store.data.gridSize,gridRotate:r=this.store.data.gridRotate}={}){this.store.data.grid=e,this.store.data.gridColor=t,this.store.data.gridSize=i<0?0:i,this.store.data.gridRotate=r,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)}setRule({rule:e=this.store.data.rule,ruleColor:t=this.store.data.ruleColor}={}){this.store.data.rule=e,this.store.data.ruleColor=t,this.store.patchFlagsTop=!0}open(e,t=!0){if(this.clear(!1,e==null?void 0:e.template),this.canvas.autoPolylineFlag=!0,e){e.theme&&this.setTheme(e.theme),this.setBackgroundImage(e.bkImage,e),Object.assign(this.store.data,e),this.store.data.pens=[];for(const i of e.pens)i.id||(i.id=fs()),!i.calculative&&(i.calculative={canvas:this.canvas}),this.store.pens[i.id]=i;for(const i of e.pens)this.canvas.makePen(i)}if(this.canvas.patchFlagsLines.forEach(i=>{i.type&&this.canvas.initLineRect(i)}),this.store.data.template||(this.store.data.template=fs()),t||(this.canvas.opening=!0),this.doInitJS(),this.doInitFn(),this.initBindDatas(),this.initBinds(),this.initMessageEvents(),this.initGlobalTriggers(),this.startAnimate(),this.startVideo(),this.listenSocket(),this.connectSocket(),this.connectNetwork(),this.startDataMock(),this.canvas.initGlobalStyle(),this.render(),setTimeout(()=>{const i=this.store.data.pens.find(r=>r.autofocus);i&&this.focus(i.id)},100),this.store.data.iconUrls)for(const i of this.store.data.iconUrls)bft(i,()=>{this.render()});this.canvas.autoPolylineFlag=!1,this.store.emitter.emit("opened"),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.init()}cacheData(e){if(e&&this.store.options.cacheLength){let t=this.store.cacheDatas.findIndex(i=>i.data&&i.data._id===e);if(t===-1)this.store.cacheDatas.push({data:bt(this.store.data,!0)}),this.store.cacheDatas.length>this.store.options.cacheLength&&this.store.cacheDatas.shift();else{let i=this.store.cacheDatas.splice(t,1)[0];this.store.cacheDatas.push(i)}}}loadCacheData(e){let t=this.store.cacheDatas.findIndex(i=>i.data&&i.data._id===e);t!==-1&&(this.store.data=this.store.cacheDatas[t].data,this.setBackgroundImage(this.store.data.bkImage),this.store.pens={},this.store.data.pens.forEach(i=>{i.calculative.canvas=this.canvas,this.store.pens[i.id]=i,Lr.path2dDraws[i.name]&&this.store.path2dMap.set(i,Lr.path2dDraws[i.name](i)),i.type&&this.store.path2dMap.set(i,Lr.path2dDraws[i.name](i)),i.image&&(i.calculative.imageDrawed=!1,this.canvas.loadImage(i))}),this.render())}statistics(){const e=this.store.data.pens.length,t=this.store.data.pens.filter(o=>o.image).length,i=this.store.data.pens.filter(o=>o.image&&o.calculative.inView).length,r=this.store.data.pens.filter(o=>o.name.endsWith("Dom")||xNe.includes(o.name)||this.store.options.domShapes.includes(o.name)||o.externElement).length,n=this.store.animates.size;let a=0;return Object.keys(this.store.bind).forEach(o=>{a+=this.store.bind[o].length}),Object.keys(this.store.bindDatas).forEach(o=>{a+=this.store.bindDatas[o].length}),{图元总数量:e,图片图元数量:t,图片图元绘制数量:i,dom图元数量:r,正在执行的动画数量:n,数据点数量:a}}initBindDatas(){this.store.bindDatas={},this.store.data.pens.forEach(e=>{var t;(t=e.form)==null||t.forEach(i=>{let r;i.dataIds&&(Array.isArray(i.dataIds)?r=i.dataIds:r=[i.dataIds]),r==null||r.forEach(n=>{this.store.bindDatas[n.dataId]||(this.store.bindDatas[n.dataId]=[]),this.store.bindDatas[n.dataId].push({id:e.id,formItem:i})})})})}initBinds(){this.jetLinksList=[],this.store.bind={},this.store.data.pens.forEach(e=>{var t;(t=e.realTimes)==null||t.forEach(i=>{if(i.bind&&i.bind.id){let r=i.productId||e.productId,n=i.deviceId||e.deviceId,a=i.propertyId,o=!1;if(r&&r.indexOf("${")>-1){let l=r.match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));l!=null&&l.length&&(r=this.getDynamicParam(l[0])||r),o=!0}if(n&&n.indexOf("${")>-1){let l=n.match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));l!=null&&l.length&&(n=this.getDynamicParam(l[0])||n),o=!0}if(a&&a.indexOf("${")>-1){let l=a.match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));l!=null&&l.length&&(a=this.getDynamicParam(l[0])||a),o=!0}if(o&&i.bind&&(i.bind.id=r+"#"+n+"#"+a),this.store.bind[i.bind.id]||(this.store.bind[i.bind.id]=[]),this.store.bind[i.bind.id].push({id:e.id,key:i.key}),r&&n&&a){const l=this.jetLinksList.findIndex(c=>c.topic.startsWith(`/${r}/${n}`));l>-1?this.jetLinksList[l].properties.includes(i.propertyId)||this.jetLinksList[l].properties.push(i.propertyId):this.jetLinksList.push({topic:`/${r}/${n}`,deviceId:n,properties:[i.propertyId]})}}})})}connectSocket(){this.connectWebsocket(),this.connectMqtt(),this.connectHttp()}doInitJS(){const e=this.store.data.initJs;if(e&&e.trim())try{new Function("context",e)({meta2d:this})}catch(t){console.warn("initJs error",t)}}doInitFn(){let e=M5(),t=[];for(let i in e)e.hasOwnProperty(i)&&i.startsWith("bind-")&&t.push({id:i.replace("bind-",""),dataId:i.replace("bind-",""),value:e[i]});t.length&&this.setDatas(t,{history:!1})}drawLine(e){e&&rFe(this.store),this.canvas.drawingLineName=e}alignPenToGrid(e){this.canvas.alignPenToGrid(e)}drawingPencil(){this.canvas.drawingPencil()}stopPencil(){this.canvas.stopPencil()}lock(e){this.store.data.locked=e,this.finishDrawLine(!0),this.canvas.drawingLineName="",this.stopPencil(),this.store.data.pens.forEach(t=>{var i;t.externElement===!0&&(i=t.calculative.singleton)!=null&&i.div&&Ha(t,t.calculative.singleton.div)}),e>0&&this.initMessageEvents()}async finishDrawLine(e){await this.canvas.finishDrawline(e)}async finishPencil(){await this.canvas.finishPencil()}updateLineType(e,t){if(!e||e.name!="line"||!t||!this.canvas[t])return;e.lineName=t;const i=rl(e),r=Dn(e);i.prev=void 0,i.next=void 0,r.prev=void 0,r.next=void 0,e.calculative.worldAnchors=[i,r],e.calculative.activeAnchor=i,this.canvas[t](this.store,e,r),e.lineName==="curve"&&(i.prev={penId:i.penId,x:i.x-50,y:i.y},i.next={penId:i.penId,x:i.x+50,y:i.y},r.prev={penId:r.penId,x:r.x-50,y:r.y},r.next={penId:r.penId,x:r.x+50,y:r.y}),e.calculative.activeAnchor=void 0,this.canvas.initLineRect(e),this.render()}addDrawLineFn(e,t){this.canvas[e]=t,this.canvas.drawLineFns.push(e)}removeDrawLineFn(e){const t=this.canvas.drawLineFns.indexOf(e);t>-1&&this.canvas.drawLineFns.splice(t,1)}showMagnifier(){this.canvas.showMagnifier()}hideMagnifier(){this.canvas.hideMagnifier()}toggleMagnifier(){this.canvas.toggleMagnifier()}clear(e=!0,t){var i;for(const r of this.store.data.pens)(i=r.onDestroy)==null||i.call(r,r);_ft(this.store,t),this.hideInput(),this.canvas.tooltip.hide(),this.map&&this.map.isShow&&(this.map.show(),this.map.setView()),this.canvas.clearCanvas(),sessionStorage.removeItem("page"),this.store.clipboard=void 0,this.store.sameTemplate||(this.canvas.canvasTemplate.bgPatchFlags=!0),this.store.patchFlagsBackground=!0,this.store.patchFlagsTop=!0,this.setBackgroundImage(void 0),e&&this.render()}emit(e,t){this.store.emitter.emit(e,t)}on(e,t){return this.store.emitter.on(e,t),this}off(e,t){return this.store.emitter.off(e,t),this}registerMoveDock(e){this.canvas.customMoveDock=e}registerResizeDock(e){this.canvas.customResizeDock=e}find(e){return this.canvas.find(e)}findOne(e){return this.canvas.findOne(e)}getPenRect(e){return this.canvas.getPenRect(e)}setPenRect(e,t,i=!0){this.canvas.setPenRect(e,t,i)}startAnimate(e,t){this.stopAnimate(e);let i;e?typeof e=="string"?i=this.find(e):i=e:i=this.store.data.pens.filter(r=>(r.type||r.frames)&&r.autoPlay||r.animations&&r.animations.length&&r.animations.findIndex(n=>n.autoPlay)!==-1),i.length&&(i.forEach(r=>{var n,a;if(r.calculative.pause){const o=Date.now()-r.calculative.pause;r.calculative.pause=void 0,r.calculative.frameStart+=o,r.calculative.frameEnd+=o}else{let o=-1;if(t!==void 0&&r.animations){if(typeof t=="string"){if(o=r.animations.findIndex(l=>l.name===t),o===-1)return}else if(typeof t=="number")if(r.animations.length>t)o=t;else return}else t===void 0&&(o=(n=r.animations)==null?void 0:n.findIndex(l=>l.autoPlay),o===-1&&((a=r.animations)!=null&&a.length)&&(o=0));if(o!==-1&&o!==void 0){const l=bt(r.animations[o]);l.animateName=l.name,delete l.name,l.currentAnimation=o,!r.type&&l.frames&&(l.showDuration=this.calcAnimateDuration(l)),this.setValue({id:r.id,...l},{doEvent:!1,history:!1})}this.store.animates.add(r),r.type||this.store.animateMap.set(r,r.calculative.canvas.getFrameProps(r))}}),this.initImageCanvas(i),this.canvas.animate())}pauseAnimate(e){let t=[];e?typeof e=="string"?t=this.find(e):t=e:this.store.animates.forEach(i=>{t.push(i)}),t.forEach(i=>{i.calculative.pause||(i.calculative.pause=Date.now())})}stopAnimate(e){let t=[];e?typeof e=="string"?t=this.find(e):t=e:this.store.animates.forEach(i=>{t.push(i)}),t.forEach(i=>{i.currentAnimation=void 0,i.calculative.pause=void 0,i.calculative.start=void 0,i.calculative.duration=void 0,i.calculative.animatePos=0,this.store.animates.delete(i),this.canvas.restoreNodeAnimate(i),this.canvas.updateLines(i),this.store.animateMap.delete(i)}),this.initImageCanvas(t),setTimeout(()=>{var i;(i=this.canvas)==null||i.calcActiveRect(),this.render()},20)}startVideo(e){let t;e?typeof e=="string"?t=this.find(e):t=e:t=this.store.data.pens.filter(i=>(i.video||i.audio)&&i.autoPlay),t.forEach(i=>{var r,n;(r=i.calculative.media)==null||r.play(),(n=i.onStartVideo)==null||n.call(i,i)})}pauseVideo(e){let t=[];e?typeof e=="string"?t=this.find(e):t=e:t=this.store.data.pens.filter(i=>(i.video||i.audio)&&i.autoPlay),t.forEach(i=>{var r,n;(r=i.calculative.media)==null||r.pause(),(n=i.onPauseVideo)==null||n.call(i,i)})}stopVideo(e){let t=[];e?typeof e=="string"?t=this.find(e):t=e:t=this.store.data.pens.filter(i=>(i.video||i.audio)&&i.autoPlay),t.forEach(i=>{var r;i.calculative.media&&(i.calculative.media.currentTime=0,i.calculative.media.pause()),(r=i.onStopVideo)==null||r.call(i,i)})}calcAnimateDuration(e){return e.frames.reduce((t,i)=>t+i.duration,0)}combine(e=this.store.active,t,i=!0){if(!e||!e.length)return;const r=bt(e);if(e.length===1&&e[0].type){e[0].type=Kn.Node,this.canvas.active(e),this.pushHistory({type:ur.Update,initPens:r,pens:bt(e,!0)}),this.render();return}const n=Um(e);let a={id:fs(),name:"combine",...n,children:[],showChild:t};this.canvas.makePen(a);const o=bt(a);let l=1/0;return e.forEach(c=>{const u=this.store.data.pens.findIndex(d=>d.id===c.id);if(u{sv(c,!0)}),this.initImageCanvas([a])),this.store.emitter.emit("combine",[a]),this.render(),a}uncombine(e){if(!e&&this.store.active&&(e=this.store.active[0]),!e||!e.children)return;const t=e.children.map(n=>this.store.pens[n]);let i=bt(t);t.forEach(n=>{n.parentId=void 0,n.x=n.calculative.worldRect.x,n.y=n.calculative.worldRect.y,n.width=n.calculative.worldRect.width,n.height=n.calculative.worldRect.height,n.locked=qs.None,n.calculative.active=void 0,n.calculative.hover=!1,this.setVisible(n,!0)});const r=this.isCombine(e)?3:2;this.pushHistory({type:ur.Update,initPens:i,pens:t,step:r}),i=[bt(e)],e.children=void 0,this.pushHistory({type:ur.Update,initPens:i,pens:[e],step:r}),this.isCombine(e)&&(this.delete([e]),this.store.histories[this.store.histories.length-1].step=r),this.inactive()}appendChild(e=this.store.active){if(!e||e.length<2)return;const t=e.findIndex(i=>i.name==="combine"&&i.showChild!==void 0);if(t!==-1){let i=e[t];const r=Um(e);Object.assign(i,r),Object.assign(i.calculative.worldRect,r),eP(i),i.children.forEach(n=>{const a=this.store.pens[n],o=yy(a.calculative.worldRect,r);Object.assign(a,o)}),e.forEach(n=>{if(n.id!==i.id){i.children.push(n.id),n.parentId=i.id;const a=yy(n.calculative.worldRect,r);Object.assign(n,a),n.locked=n.lockedOnCombine??qs.DisableMove,n.locked=n.interaction||Pse.includes(n.name)?0:n.locked,sv(n,!0)}}),this.initImageCanvas(e),this.render()}else console.warn("Invalid operation!")}updateRectbyChild(e,t,i){if(Go(e),ro(e),t.calculative.worldRect=e,ov(e,i.calculative.worldRect,!0)){const r=yy(e,i.calculative.worldRect);Object.assign(t,r)}else{let r=Math.min(e.x,i.calculative.worldRect.x),n=Math.min(e.y,i.calculative.worldRect.y),a=Math.max(e.ex,i.calculative.worldRect.ex),o=Math.max(e.ey,i.calculative.worldRect.ey);i.calculative.worldRect={x:r,y:n,width:a-r,height:o-n,ex:a,ey:o},i.parentId||Object.assign(i,i.calculative.worldRect),ro(i.calculative.worldRect),i.children.forEach(l=>{const c=this.store.pens[l],u=yy(c.calculative.worldRect,i.calculative.worldRect);Object.assign(c,u)}),i.parentId&&this.updateRectbyChild(i.calculative.worldRect,i,this.store.pens[i.parentId])}this.canvas.updatePenRect(i),this.render()}isCombine(e){return!!(e.name==="combine"||e.children&&e.children.length>0)}active(e,t=!0){this.canvas.active(e,t)}inactive(){this.canvas.inactive()}activeAll(){this.canvas.active(this.store.data.pens.filter(e=>!e.parentId&&e.locked!==qs.Disable)),this.render()}focus(e){const t=this.findOne(e);t&&(this.store.hover=t,this.store.hover.calculative.hover=!0,this.showInput(t))}delete(e,t=!1,i=!0){this.canvas.delete(e,t,i)}scale(e,t={x:0,y:0}){this.canvas.scale(e,t)}translate(e,t){this.canvas.translate(e,t)}translatePens(e,t,i){this.canvas.translatePens(e,t,i)}getParent(e,t){return Uf(e,t)}getAllChildren(e){return S1(e,this.store)}getAllFollowers(e){return Bme(e,this.store)}data(){const e=bt(this.store.data),{pens:t,paths:i}=this.store.data;e.version=bNe.version,e.paths={};for(const r in i)Object.prototype.hasOwnProperty.call(i,r)&&t.find(n=>n.pathId===r)&&(e.paths[r]=i[r]);return e.dataPoints=[...Object.keys(this.store.bind),...Object.keys(this.store.bindDatas)],e}copy(e){this.canvas.copy(e)}cut(e){this.canvas.cut(e)}paste(){this.canvas.paste()}undo(){this.canvas.undo()}redo(){this.canvas.redo()}listenSocket(){try{let e;const t=this.store.data.socketCbJs;if(t&&(e=new Function("e","context",t)),!e)return this.socketFn=null,!1;this.socketFn=e}catch(e){return console.error("Create the function for socket:",e),!1}return!0}connectWebsocket(e){this.closeWebsocket(),e&&(this.store.data.websocket=e),this.store.data.websocket&&(this.websocket=new WebSocket(this.store.data.websocket,this.store.data.websocketProtocols||void 0),this.websocket.onmessage=t=>{this.socketCallback(t.data,{type:"websocket",url:this.store.data.websocket})},this.websocket.onerror=t=>{this.store.emitter.emit("error",{type:"websocket",error:t})},this.websocket.onclose=()=>{if(this.store.options.reconnetTimes&&(this.websocketTimes++,this.websocketTimes>=this.store.options.reconnetTimes)){this.websocketTimes=0,this.closeWebsocket();return}console.info("Canvas websocket closed and reconneting..."),this.connectWebsocket()})}closeWebsocket(){this.websocket&&(this.websocket.onclose=void 0,this.websocket.close(),this.websocket=void 0)}connectMqtt(e){if(this.closeMqtt(),e&&(this.store.data.mqtt=e.mqtt,this.store.data.mqttTopics=e.mqttTopics,this.store.data.mqttOptions=e.mqttOptions),this.store.data.mqtt){this.store.data.mqttOptions.clientId&&!this.store.data.mqttOptions.customClientId&&(this.store.data.mqttOptions.clientId=fs());const t={...this.store.data.mqttOptions};t.username||delete t.username,t.password||delete t.password;const{username:i,password:r}=t;i&&r||!i&&!r?(this.mqttClient=sY.connect(this.store.data.mqtt,t),this.mqttClient.on("message",(n,a)=>{this.socketCallback(a.toString(),{topic:n,type:"mqtt",url:this.store.data.mqtt})}),this.mqttClient.on("error",n=>{this.store.emitter.emit("error",{type:"mqtt",error:n})}),this.mqttClient.on("close",()=>{this.store.options.reconnetTimes&&(this.mqttTimes++,this.mqttTimes>=this.store.options.reconnetTimes&&(this.mqttTimes=0,this.closeMqtt()))}),this.store.data.mqttTopics&&this.mqttClient.subscribe(this.store.data.mqttTopics.split(","))):console.warn("缺少用户名或密码")}}closeMqtt(){var e;(e=this.mqttClient)==null||e.end()}connectHttp(){this.closeHttp();const{https:e}=this.store.data;if(e)this.store.data.cancelFirstConnect||e.forEach(async t=>{this.oldRequestHttp(t)}),e.forEach((t,i)=>{t.http&&t.httpTimeInterval!==0&&(t.times=0,this.httpTimerList[i]=setInterval(async()=>{this.oldRequestHttp(t),this.store.options.reconnetTimes&&t.times>=this.store.options.reconnetTimes&&(t.times=0,clearInterval(this.httpTimerList[i]),this.httpTimerList[i]=void 0)},t.httpTimeInterval||1e3))});else{const{http:t,httpTimeInterval:i,httpHeaders:r}=this.store.data;t&&(this.httpTimer=setInterval(async()=>{const n=await fetch(t,{headers:r});if(n.ok){const a=await n.text();this.socketCallback(a,{type:"http",url:t})}},i||1e3))}}async oldRequestHttp(e){let t=bt(e);if(t.http){const i=await fetch(t.http,{headers:t.httpHeaders,method:t.method||"GET",body:t.method==="POST"?JSON.stringify(t.body):void 0});if(i.ok){const r=await i.text();this.socketCallback(r,{type:"http",url:t.http})}else e.times++,this.store.emitter.emit("error",{type:"http",error:i})}}async sendDatabyHttp(e){const{https:t}=this.store.data;if(t)t.forEach(async i=>{i.http&&(await fetch(i.http,{method:"post",body:e,headers:i.httpHeaders})).ok&&console.info("http消息发送成功")});else{const{http:i,httpHeaders:r}=this.store.data;i&&(await fetch(i,{method:"post",body:e,headers:r})).ok&&console.info("http消息发送成功")}}closeHttp(){clearInterval(this.httpTimer),this.httpTimer=void 0,this.httpTimerList&&this.httpTimerList.forEach(e=>{clearInterval(e),e=void 0})}connectNetwork(){this.closeNetwork();const{networks:e}=this.store.data,t=[];if(e){let i=0;this.mqttClients=[];let r=0,n=0;this.websockets=[],e.forEach(async a=>{if(a.protocol==="mqtt")a.index=i,a.options.clientId&&!a.options.customClientId&&(a.options.clientId=fs()),a.times=0,this.mqttClients[i]=sY.connect(a.url,a.options),this.mqttClients[i].on("message",(o,l)=>{this.socketCallback(l.toString(),{topic:o,type:"mqtt",url:a.url})}),this.mqttClients[i].on("error",o=>{this.store.emitter.emit("error",{type:"mqtt",error:o})}),this.mqttClients[i].on("close",()=>{var o;this.store.options.reconnetTimes&&(a.times++,a.times>=this.store.options.reconnetTimes&&(a.times=0,this.mqttClients&&((o=this.mqttClients[a.index])==null||o.end())))}),a.topics&&this.mqttClients[i].subscribe(a.topics.split(",")),i+=1;else if(a.protocol==="websocket")a.index=r,this.connectNetWebSocket(a),r+=1;else if(a.protocol==="http")t.push({url:a.url,interval:a.interval,headers:a.headers||void 0,method:a.method,body:a.body});else if(a.protocol==="iot"){const o=await this.getIotToken(a.devices);a.method==="mqtt"?(a.index=i,this.mqttClients[i]=sY.connect(a.url),this.mqttClients[i].on("message",(l,c)=>{this.socketCallback(c.toString(),{topic:`le5le-iot/properties/${o}`,type:"iot",url:a.url,method:"mqtt"})}),this.mqttClients[i].on("error",l=>{this.store.emitter.emit("error",{type:"mqtt",error:l})}),this.mqttClients[i].subscribe(`le5le-iot/properties/${o}`),i+=1):a.method==="websocket"&&(a.index=r,this.websockets[r]=new WebSocket(`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/ws/iot/properties`,o),this.websockets[r].onmessage=l=>{this.socketCallback(l.data,{type:"iot",method:"websocket"})},this.websockets[r].onerror=l=>{this.store.emitter.emit("error",{type:"websocket",error:l})},r+=1)}else a.protocol==="sql"?(await this.doSqlCode("list",a.dbId,a.sql),a.interval&&(a.index=n,this.sqlTimerList[n]=setInterval(async()=>{await this.doSqlCode("list",a.dbId,a.sql)},a.interval),n+=1)):a.protocol==="ADIIOT"&&K0t(this,a)})}this.onNetworkConnect(t)}connectNetWebSocket(e){var t;this.websockets[e.index]&&(this.websockets[e.index].onclose=void 0,(t=this.websockets[e.index])==null||t.close(),this.websockets[e.index]=void 0),this.websockets[e.index]=new WebSocket(e.url,e.protocols||void 0),this.websockets[e.index].onmessage=i=>{this.socketCallback(i.data,{type:"websocket",url:e.url})},this.websockets[e.index].onerror=i=>{this.store.emitter.emit("error",{type:"websocket",error:i})},this.websockets[e.index].onclose=()=>{var i;if(this.store.options.reconnetTimes&&(e.times++,e.times>=this.store.options.reconnetTimes)){e.times=0,this.websockets[e.index].onclose=void 0,(i=this.websockets[e.index])==null||i.close(),this.websockets[e.index]=void 0;return}setTimeout(()=>{console.info("Canvas websocket closed and reconneting..."),this.connectNetWebSocket(e)},2e3)}}async getIotToken(e){const t=await fetch("/api/iot/subscribe/properties",{method:"POST",body:JSON.stringify({devices:e})});if(t.ok){const i=await t.text();return JSON.parse(i).token}}async doSqlCode(e,t,i){const r=await fetch(`/api/iot/data/sql/${e}`,{method:"POST",body:JSON.stringify({dbid:t,sql:i})});if(r.ok){const n=await r.text();n&&this.socketCallback(n,{type:"sql",url:`/api/iot/data/sql/${e}`})}}randomString(e){e=e||32;let t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",i=t.length,r="";for(let n=0;n{let n=this.mockValue(r);n!==void 0&&e.push({id:r.id,value:n})}),e.length&&this.setDatas(e,{render:!0,doEvent:!0,history:!1})}startDataMock(){this.store.data.enableMock&&(this.stopDataMock(),this.initBinds(),this.updateTimer=setInterval(()=>{this.store.data.pens.forEach(t=>{this.penMock(t)}),this.dataMock(),this.render()},this.store.data.networkInterval||1e3))}stopDataMock(){clearInterval(this.updateTimer),this.updateTimer=void 0}penMock(e){var t;if(e.realTimes){let i={};if(e.realTimes.forEach(r=>{let n=this.mockValue(r);n!==void 0&&(i[r.key]=n)}),Object.keys(i).length){let r=e.onBeforeValue?e.onBeforeValue(e,i):i;this.canvas.updateValue(e,r),(t=e.onValue)==null||t.call(e,e),this.store.emitter.emit("valueUpdate",e)}}}penNetwork(e){const t={url:e.apiUrl,method:e.apiMethod,headers:e.apiHeaders,body:e.apiBody};this.requestHttp(t),e.apiEnable?(this.store.pensNetwork||(this.store.pensNetwork={}),this.store.pensNetwork[e.id]=t):delete this.store.pensNetwork[e.id]}getDynamicParam(e){return M5()[e]||localStorage[e]||Y$(e)||""}onNetworkConnect(e){if(e&&e.length){if(this.store.pensNetwork)for(let t in this.store.pensNetwork)e.push(this.store.pensNetwork[t]);this.store.data.cancelFirstConnect||e.forEach(async t=>{this.requestHttp(t)}),e.forEach((t,i)=>{t.times=0,t.interval!==0&&(this.updateTimerList[i]=setInterval(async()=>{this.requestHttp(t),this.store.options.reconnetTimes&&t.times>=this.store.options.reconnetTimes&&(t.times=0,clearInterval(this.updateTimerList[i]),this.updateTimerList[i]=void 0)},t.interval||1e3))})}}async requestHttp(e){var i,r,n;let t=bt(e);if(t.url){if(t.url.indexOf("${")>-1){let o=(i=t.url.match(/\$\{([^}]+)\}/g))==null?void 0:i.map(l=>l.slice(2,-1));o&&o.forEach(l=>{t.url=t.url.replace(`\${${l}}`,this.getDynamicParam(l))})}if(typeof t.headers=="object"){for(let o in t.headers)if(typeof t.headers[o]=="string"){let l=(r=t.headers[o].match(/\$\{([^}]+)\}/g))==null?void 0:r.map(c=>c.slice(2,-1));l&&(t.headers[o]=t.headers[o].replace(`\${${l[0]}}`,this.getDynamicParam(l[0])))}}if(typeof t.body=="object"){for(let o in t.body)if(typeof t.body[o]=="string"){let l=(n=t.body[o].match(/\$\{([^}]+)\}/g))==null?void 0:n.map(c=>c.slice(2,-1));l&&(t.body[o]=t.body[o].replace(`\${${l[0]}}`,this.getDynamicParam(l[0])))}}const a=await fetch(t.url,{headers:t.headers,method:t.method,body:t.method==="GET"?void 0:JSON.stringify(t.body)});if(a.ok){const o=await a.text();this.socketCallback(o,{type:"http",url:t.url})}else e.times++,this.store.emitter.emit("error",{type:"http",error:a})}}closeNetwork(){this.mqttClients&&this.mqttClients.forEach(e=>{e.end()}),this.websockets&&this.websockets.forEach(e=>{e&&(e.onclose=void 0,e.close(),e=void 0)}),this.mqttClients=void 0,this.websockets=void 0,this.updateTimerList&&this.updateTimerList.forEach(e=>{clearInterval(e),e=void 0}),this.sqlTimerList&&this.sqlTimerList.forEach(e=>{clearInterval(e),e=void 0}),H0t(this)}socketCallback(e,t){this.store.emitter.emit("socket",{message:e,context:t});let i=e;if(this.socketFn&&(i=this.socketFn(e,{meta2d:this,type:t.type,topic:t.topic,url:t.url,method:t.method}),!i))return;i===!0&&(i=e);let r;if(i.constructor===Object||i.constructor===Array)r=i;else if(typeof i=="string")try{r=JSON.parse(i)}catch(n){console.warn("Invalid socket data:",r,n)}else return;r&&(Array.isArray(r)||(r=[r]),r.length&&(r[0].dataId?this.setDatas(r):r.forEach(n=>{this.setValue(n)})))}setDatas(e,{render:t=!0,doEvent:i=!0,history:r}={}){const n=new Map;e.forEach(l=>{var c,u;(c=this.store.bindDatas[l.dataId])==null||c.forEach(h=>{const d=this.store.pens[h.id];if(!d)return;let f=n.get(d);if(!d.noOnBinds&&typeof d.onBinds=="function"){if(f)return;n.set(d,d.onBinds(d,e,h.formItem));return}f?f[h.formItem.key]=l.value:(f={id:h.id,[h.formItem.key]:l.value},n.set(d,f))}),(u=this.store.bind[l.id||l.dataId])==null||u.forEach(h=>{const d=this.store.pens[h.id];if(!d)return;let f=n.get(d);f?f[h.key]=l.value:(f={id:h.id,[h.key]:l.value},n.set(d,f))})}),this.store.data.locked&&this.doDataEvent(e);let a,o;r&&(a=[]),n.forEach((l,c)=>{this.setValue(l,{render:!1,doEvent:i,history:!1}),r&&(a.push(bt(c,!0)),o.push(c))}),t&&this.render(),r&&this.pushHistory({type:ur.Update,initPens:a,pens:o})}setValue(e,{render:t=!0,doEvent:i=!0,history:r}={}){let n=[];if(!e)return;if(e.id){if(e.id===this.store.data.id){this.setDatabyOptions(e),e.bkImage&&this.setBackgroundImage(e.bkImage),e.background&&this.setBackgroundColor(e.background),this.render();return}const o=this.store.pens[e.id];if(o)n=[o];else{let l=this.store.bind[e.id];if(l&&l.length){n=[],this.setDatas([e],{render:t,doEvent:i,history:r});return}}}else if(e.dataId){n=[],this.setDatas([e],{render:t,doEvent:i,history:r});return}else if(e.tag)n=this.find(e.tag);else{let o=[];for(let l in e)o.push({dataId:l,id:l,value:e[l]});o.length&&this.setDatas(o,{render:t,doEvent:i,history:r});return}r=r&&!this.store.data.locked;let a;if(r&&(a=bt(n)),n.forEach(o=>{var c;const l=o.onBeforeValue?o.onBeforeValue(o,e):e;e.frames&&(this.stopAnimate([o]),e.showDuration||(e.showDuration=e.frames.reduce((u,h)=>u+h.duration,0))),Gme(o,l),this.canvas.updateValue(o,l),(c=o.onValue)==null||c.call(o,o)}),!this.store.data.locked&&this.store.active.length&&!this.canvas.movingPens&&this.canvas.calcActiveRect(),r){let o=bt(n);this.pushHistory({type:ur.Update,initPens:a,pens:o})}i&&n.forEach(o=>{this.store.emitter.emit("valueUpdate",o)}),t&&this.render()}_setValue(e,t=!1){this.setValue(e,{history:t,render:!1,doEvent:!1})}pushHistory(e){this.canvas.pushHistory(e)}showInput(e,t){this.canvas.showInput(e,t)}hideInput(){this.canvas.hideInput()}clearDropdownList(){this.canvas.clearDropdownList()}clearRuleLines(){this.canvas.clearRuleLines()}doMessageEvent(e,t){this.store.messageEvents[e]&&this.store.messageEvents[e].forEach(i=>{let r=!1;i.event.conditions&&i.event.conditions.length?i.event.conditionType==="and"?r=i.event.conditions.every(n=>this.judgeCondition(i.pen,n.key,n)):i.event.conditionType==="or"&&(r=i.event.conditions.some(n=>this.judgeCondition(i.pen,n.key,n))):r=!0,r&&i.event.actions.forEach(n=>{this.events[n.action](i.pen,n,t)})})}initGlobalTriggers(){var e;this.store.globalTriggers={},(e=this.store.data.triggers)==null||e.forEach(t=>{t.conditions.forEach(i=>{i.source&&(this.store.globalTriggers[i.source]||(this.store.globalTriggers[i.source]=[]),this.store.globalTriggers[i.source].includes(t)||this.store.globalTriggers[i.source].push(t))})})}initMessageEvents(){this.store.messageEvents={},this.store.data.pens.forEach(e=>{var t;(t=e.events)==null||t.forEach(i=>{i.name==="message"&&i.message&&(this.store.messageEvents[i.message]||(this.store.messageEvents[i.message]=[]),this.store.messageEvents[i.message].push({pen:e,event:i}))})})}dataJudegeCondition(e,t,i){const{type:r,target:n,fnJs:a,fn:o,operator:l,valueType:c}=i;let u=!1;if(r==="fn"){if(o)u=o(e,{meta2d:this});else if(a){try{i.fn=new Function("data","context",a)}catch(h){console.error("Error: make function:",h)}i.fn&&(u=i.fn(e,{meta2d:this}))}}else{let h=i.value;c==="prop"&&(h=e[i.value]);let d=e[t];switch(l){case">":u=d>+h;break;case">=":u=d>=+h;break;case"<":u=d<+h;break;case"<=":u=d<=+h;break;case"=":case"==":u=d==h;break;case"!=":u=d!=h;break;case"[)":u=II(+d,h);break;case"![)":u=!II(+d,h);break;case"[]":u=PI(d,h);break;case"![]":u=!PI(d,h);break}}return u}judgeCondition(e,t,i){const{type:r,target:n,fnJs:a,fn:o,operator:l,valueType:c}=i;let u=!1;if(r==="fn"){if(o)u=o(e,{meta2d:this});else if(a){try{i.fn=new Function("pen","context",a)}catch(h){console.error("Error: make function:",h)}i.fn&&(u=i.fn(e,{meta2d:this}))}}else{let h=i.value;c==="prop"&&(h=this.store.pens[n][i.value]);let d=oS(e,t);switch(["x","y","width","height"].includes(t)&&(d=this.getPenRect(e)[t]),l){case">":u=d>+h;break;case">=":u=d>=+h;break;case"<":u=d<+h;break;case"<=":u=d<=+h;break;case"=":case"==":u=d==h;break;case"!=":u=d!=h;break;case"[)":u=II(+d,h);break;case"![)":u=!II(+d,h);break;case"[]":u=PI(d,h);break;case"![]":u=!PI(d,h);break}}return u}pushChildren(e,t){const i=[bt(e,!0)],r=[];e.children||(e.children=[]);const n=[];t.forEach(o=>{let l=bt(o,!0);if((!o.id||!this.store.pens[o.id])&&(this.canvas.makePen(o),l=null),o.parentId){const u=this.store.pens[o.parentId],h=u.children.findIndex(d=>d===o.id);i.push(bt(u,!0)),u.children.splice(h,1),n.push(bt(u,!0))}e.children.push(o.id),o.parentId=e.id;const c=yy(o.calculative.worldRect,e.calculative.worldRect);Object.assign(o,c),o.locked=o.lockedOnCombine??qs.DisableMove,o.locked=o.interaction||Pse.includes(o.name)?0:o.locked,l?(i.push(l),n.push(bt(o,!0))):r.push(bt(o,!0))}),n.push(bt(e,!0));let a=1;r.length&&(a=2,this.pushHistory({type:ur.Add,pens:r,step:a})),this.pushHistory({type:ur.Update,initPens:i,pens:n,step:a})}toPng(e,t,i=!1,r){return this.canvas.toPng(e,t,i,r)}activeToPng(e,t){return this.canvas.activeToPng(e,t)}pensToPng(e=this.store.active,t,i){return this.canvas.pensToPng(e,t,i)}downloadPng(e,t,i){var r;for(const n of this.store.data.pens)(n.calculative.img||["iframe"].includes(n.name))&&((r=n.onRenderPenRaw)==null||r.call(n,n));setTimeout(()=>{const n=document.createElement("a");n.setAttribute("download",(e||this.store.data.name||"le5le.meta2d")+".png"),n.setAttribute("href",this.toPng(t,void 0,!0,i));const a=document.createEvent("MouseEvents");a.initEvent("click",!0,!0),n.dispatchEvent(a)},1e3)}downloadSvg(){if(!window.C2S)throw console.error("请先加载乐吾乐官网下的canvas2svg.js","https://assets.le5lecdn.com/2d/canvas2svg.js"),new Error("请先加载乐吾乐官网下的canvas2svg.js");let e=!1;const t=this.store.data.width||this.store.options.width,i=this.store.data.height||this.store.options.height;t&&i&&!this.store.data.component&&(e=!0);const r=this.getRect();e&&(r.x=this.store.data.origin.x,r.y=this.store.data.origin.y,r.width=t*this.store.data.scale,r.height=i*this.store.data.scale),r.x-=10,r.y-=10;const n=new window.C2S(r.width+20,r.height+20);n.textBaseline="middle",n.strokeStyle=this.store.styles.color;const a=this.store.data.background||this.store.styles.background;a&&e&&(n.save(),n.fillStyle=a,n.fillRect(0,0,r.width,r.height),n.restore()),this.store.bkImg&&e&&n.drawImage(this.store.bkImg,0,0,r.width,r.height),a&&!e&&(n.save(),n.fillStyle=a,n.fillRect(0,0,r.width+20,r.height+20),n.restore());for(const f of this.store.data.pens)f.visible==!1||!Z$(f,this.store)||f.name==="combine"&&!f.draw||$$(n,f,r,!0);let o=n.getSerializedSvg();this.store.data.background?(o=o.replace("{{bk}}",""),o=o.replace("{{bkRect}}",``)):(o=o.replace("{{bk}}",""),o=o.replace("{{bkRect}}","")),o=o.replace(/--le5le--/g,"&#x");const l=window.URL,c=new Blob([o]),u=l.createObjectURL(c),h=document.createElement("a");h.setAttribute("download",`${this.store.data.name||"le5le.meta2d"}.svg`),h.setAttribute("href",u);const d=document.createEvent("MouseEvents");d.initEvent("click",!0,!0),h.dispatchEvent(d)}getRect(e=this.store.data.pens){return Um(e)}hiddenTemplate(){this.canvas.canvasTemplate.hidden()}showTemplate(){this.canvas.canvasTemplate.show()}lockTemplate(e){this.store.data.pens.forEach(t=>{t.canvasLayer===hn.CanvasTemplate&&(t.locked=e)})}fitView(e=!0,t=10){var h,d;if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:r,offsetHeight:n}=i;this.resize(r,n);const a=rv(t),o=this.getRect(),l=(r-a[1]-a[3])/o.width,c=(n-a[0]-a[2])/o.height;let u=l;e?u=l>c?c:l:u=l>c?l:c,(h=this.store.data.fits)!=null&&h.length&&(this.canvas.opening=!0),this.scale(u*this.store.data.scale),this.centerView(),(d=this.store.data.fits)!=null&&d.length&&this.fillView()}fillView(){var r,n;const e=this.getRect(),t=this.canvas.width-e.width,i=this.canvas.height-e.height;if(Math.abs(t)>10){(r=this.store.data.fits)==null||r.forEach(o=>{let l=[];o.children.forEach(u=>{this.store.pens[u].locked=qs.None,l.push(this.store.pens[u])});let c=t/2;if(o.left&&o.right){let u=o.leftValue,h=o.rightValue;u?u=Math.abs(u)<1?u*this.canvas.width:u:u=0,h?h=Math.abs(h)<1?h*this.canvas.width:h:h=0;let d=(this.canvas.width-u-h)/(e.width-u-h);l.forEach(f=>{var p;f.image&&f.imageRatio&&f.calculative.worldRect.width/this.canvas.width>.1&&(f.imageRatio=!1),f.calculative.worldRect.x=e.x-t/2+u+(f.calculative.worldRect.x-e.x)*d,f.calculative.worldRect.width*=d,f.calculative.worldRect.ex=f.calculative.worldRect.x+f.calculative.worldRect.width,f.calculative.width=f.calculative.worldRect.width,f.calculative.x=f.calculative.worldRect.x,f.width=f.calculative.worldRect.width,f.x=f.calculative.worldRect.x,this.canvas.updatePenRect(f,{worldRectIsReady:!1}),f.externElement&&((p=f.onResize)==null||p.call(f,f))})}else o.left?(c=-c,o.leftValue&&(c+=Math.abs(o.leftValue)<1?o.leftValue*this.canvas.width:o.leftValue),this.translatePens(l,c,0)):o.right&&(o.rightValue&&(c=c-(Math.abs(o.rightValue)<1?o.rightValue*this.canvas.width:o.rightValue)),this.translatePens(l,c,0))});const a=this.store.data.pens.filter(o=>o.name==="iframe");a==null||a.forEach(o=>{var c,u;const l=o.calculative.worldRect;if(l.width/this.store.data.scale>e.width*.8){let h=l.width;o.calculative.worldRect.x=l.x-t/2,o.calculative.worldRect.width=l.width+t,o.calculative.worldRect.ex=l.ex+t,o.operationalRect.x=o.operationalRect.x*h/o.calculative.worldRect.width,o.operationalRect.width=(o.calculative.worldRect.width-(1-o.operationalRect.width)*h)/o.calculative.worldRect.width,(c=o.onBeforeValue)==null||c.call(o,o,{operationalRect:o.operationalRect}),(u=o.onResize)==null||u.call(o,o)}})}if(Math.abs(i)>10){(n=this.store.data.fits)==null||n.forEach(o=>{let l=[];o.children.forEach(u=>{this.store.pens[u].locked=qs.None,l.push(this.store.pens[u])});let c=i/2;if(o.top&&o.bottom){let u=o.topValue,h=o.bottomValue;u?u=Math.abs(u)<1?u*this.canvas.height:u:u=0,h?h=Math.abs(h)<1?h*this.canvas.height:h:h=0;let d=(this.canvas.height-u-h)/(e.height-u-h);l.forEach(f=>{var p;f.image&&f.imageRatio&&f.calculative.worldRect.height/this.canvas.height>.1&&(f.imageRatio=!1),f.calculative.worldRect.y=e.y-i/2+u+(f.calculative.worldRect.y-e.y)*d,f.calculative.worldRect.height*=d,f.calculative.worldRect.ey=f.calculative.worldRect.y+f.calculative.worldRect.height,f.calculative.height=f.calculative.worldRect.height,f.calculative.y=f.calculative.worldRect.y,f.height=f.calculative.worldRect.height,f.y=f.calculative.worldRect.y,this.canvas.updatePenRect(f,{worldRectIsReady:!1}),f.externElement&&((p=f.onResize)==null||p.call(f,f))})}else o.top?(c=-c,o.topValue&&(c+=Math.abs(o.topValue)<1?o.topValue*this.canvas.height:o.topValue),this.translatePens(l,0,c)):o.bottom&&(o.bottomValue&&(c=c-(Math.abs(o.bottomValue)<1?o.bottomValue*this.canvas.height:o.bottomValue)),this.translatePens(l,0,c))});const a=this.store.data.pens.filter(o=>o.name==="iframe");a==null||a.forEach(o=>{var c,u;const l=o.calculative.worldRect;if(l.height/this.store.data.scale>e.height*.8){let h=l.height;o.calculative.worldRect.y=l.y-i/2,o.calculative.worldRect.height=l.height+i,o.calculative.worldRect.ey=l.ey+i,o.operationalRect.y=o.operationalRect.y*h/o.calculative.worldRect.width,o.operationalRect.height=(o.calculative.worldRect.height-(1-o.operationalRect.height)*h)/o.calculative.worldRect.height,(c=o.onBeforeValue)==null||c.call(o,o,{operationalRect:o.operationalRect}),(u=o.onResize)==null||u.call(o,o)}})}this.canvas.canvasTemplate.fit=!0,this.canvas.canvasTemplate.init(),this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.render(!0)}trimPens(){let e=this.store.data.pens.filter(t=>t.name==="line"&&t.anchors.length<2);this.delete(e)}fitTemplateView(e=!0,t=10){if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:r,offsetHeight:n}=i,a=rv(t),o=this.getRect(),l=(r-a[1]-a[3])/o.width,c=(n-a[0]-a[2])/o.height;let u=l;e?u=l>c?c:l:u=l>c?l:c,this.canvas.templateScale(u*this.store.data.scale);let h=this.getRect(),d=this.store.data.pens.filter(f=>!f.parentId);this.canvas.templateTranslatePens(d,-h.x,-h.y),this.store.data.pens.forEach(f=>{f.type?this.canvas.initLineRect(f):this.canvas.updateLines(f)}),this.centerView()}fitSizeView(e=!0,t=10){var d,f;const{canvas:i}=this.canvas,{offsetWidth:r,offsetHeight:n}=i;this.resize(r,n);const a=rv(t),o=(this.store.data.width||this.store.options.width)*this.store.data.scale,l=(this.store.data.height||this.store.options.height)*this.store.data.scale,c=(r-a[1]-a[3])/o,u=(n-a[0]-a[2])/l;let h=c;e==="width"?h=c:e==="height"?h=u:e?h=c>u?u:c:h=c>u?c:u,(d=this.store.data.fits)!=null&&d.length&&(this.canvas.opening=!0),this.scale(h*this.store.data.scale),this.centerSizeView(),(f=this.store.data.fits)!=null&&f.length&&this.fillView()}centerSizeView(){const e=this.getViewCenter(),t=this.store.data.width||this.store.options.width,i=this.store.data.height||this.store.options.height,r={x:0,y:0,width:t,height:i};ro(r);const{center:n}=r,{scale:a,origin:o,x:l,y:c}=this.store.data;this.translate((e.x-o.x)/a-n.x-l/a,(e.y-o.y)/a-n.y-c/a);const{canvas:u}=this.canvas,h=(u.scrollWidth-u.offsetWidth)/2,d=(u.scrollHeight-u.offsetHeight)/2;u.scrollTo(h,d)}scrollView(e=10,t=!1){if(!this.hasView()||!this.canvas.scroll)return;const{canvas:i}=this.canvas,{offsetWidth:r,offsetHeight:n}=i;this.resize(r,n);const a=rv(e),o=this.getRect(),l=(r-a[1]-a[3])/o.width;this.scale(l*this.store.data.scale),this.topView(a[0]),t&&this.canvas.scroll.changeMode()}screenView(e=10,t=!0){if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:r,offsetHeight:n}=i;this.resize(r,n);const a=rv(e),o=this.getRect();let l=(r-a[1]-a[3])/o.width;t||(l=(n-a[0]-a[2])/o.height),this.scale(l*this.store.data.scale),this.topView(a[0])}topView(e=10){if(!this.hasView())return;const t=this.getRect(),i=this.getViewCenter(),r=this.getPenRect(t);ro(r);const{center:n}=r,{scale:a,origin:o,x:l,y:c}=this.store.data;this.translate((i.x-o.x)/a-n.x-l/a,(e-o.y)/a-r.y-c/a);const{canvas:u}=this.canvas,h=(u.scrollWidth-u.offsetWidth)/2,d=(u.scrollHeight-u.offsetHeight)/2;u.scrollTo(h,d)}centerView(){if(!this.hasView())return;const e=this.getRect(),t=this.getViewCenter(),i=this.getPenRect(e);ro(i);const{center:r}=i,{scale:n,origin:a,x:o,y:l}=this.store.data;this.translate((t.x-a.x)/n-r.x-o/n,(t.y-a.y)/n-r.y-l/n);const{canvas:c}=this.canvas,u=(c.scrollWidth-c.offsetWidth)/2,h=(c.scrollHeight-c.offsetHeight)/2;c.scrollTo(u,h)}hasView(){return!!this.store.data.pens.filter(e=>!e.isRuleLine).length}getViewCenter(){const{width:e,height:t}=this.canvas;return{x:e/2,y:t/2}}beSameByFirst(e=this.store.data.pens,t){const i=bt(e),r=e[0],{width:n,height:a}=this.getPenRect(r);for(let o=1;o{r[n]=i[n]});for(let n=1;n{r[n]=i[n]});for(let n=0;n0){const i=e[0];_9.forEach(r=>{t[r]=i[r]!==void 0?i[r]:this.store.options.defaultFormat[r]||this.store.data[r]||this.store.options[r]})}else _9.forEach(i=>{this.store.options.defaultFormat[i]||this.store.data[i]||this.store.options[i]});localStorage.setItem("meta2d-formatPainter",JSON.stringify(t))}formatPainter(){const e=this.store.active,t=bt(e),i=JSON.parse(localStorage.getItem("meta2d-formatPainter"));for(let r=0;r{for(let r=0;r{c=Math.min(c,d.calculative.worldRect[h]),u=Math.max(u,d.calculative.worldRect["e"+h])}),i=(u-c)/this.store.data.scale}if(t=t.filter(c=>!c.parentId),t.length<=2)return;const r=bt(t),n=t.reduce((c,u)=>{const h=this.getPenRect(u);return c+h[e]},0),a=(i-n)/(t.length-1);t=t.sort((c,u)=>e==="width"?c.x-u.x:c.y-u.y);const o=this.getPenRect(t[0]);let l=e==="width"?o.x:o.y;for(const c of t){const u=this.getPenRect(c);e==="width"?u.x=l:u.y=l,l+=u[e]+a,this.setValue({id:c.id,...u},{render:!1,doEvent:!1})}this.initImageCanvas(t),this.initTemplateCanvas(t),this.render(),this.pushHistory({type:ur.Update,initPens:r,pens:t})}spaceBetween(e,t){this.spaceBetweenByDirection("width",e,t)}spaceBetweenColumn(e,t){this.spaceBetweenByDirection("height",e,t)}layout(e=this.store.data.pens,t,i=30){const r=this.getPenRect(Um(e));!t&&(t=r.width),e=e.filter(c=>!c.type&&!c.parentId);const n=bt(e);let a=0;e.forEach(c=>{const u=this.getPenRect(c);u.height>a&&(a=u.height)});let o=r.x,l=r.y;e.forEach((c,u)=>{const h=this.getPenRect(c);if(h.x=o,h.y=l+a/2-h.height/2,this.setValue({id:c.id,...h},{render:!1,doEvent:!1}),u===e.length-1)return;const d=o+h.width-r.x,f=this.getPenRect(e[u+1]);Math.round(t-d)>=Math.round(f.width+i)?o+=h.width+i:(o=r.x,l+=a+i)}),this.initImageCanvas(e),this.initTemplateCanvas(e),this.render(),this.pushHistory({type:ur.Update,initPens:n,pens:e})}gotoView(e){const t=this.getViewCenter(),i=t.x-e.calculative.worldRect.x-e.calculative.worldRect.width/2,r=t.y-e.calculative.worldRect.y-e.calculative.worldRect.height/2;this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.translate(i-this.store.data.x,r-this.store.data.y),this.store.data.x=i,this.store.data.y=r;for(const n of this.store.data.pens)sv(n);this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.render()}showMap(){this.map||(this.map=new G0t(this.canvas)),this.map.show()}hideMap(){this.map.hide()}onSizeUpdate(){this.mapTimer&&(clearTimeout(this.mapTimer),this.mapTimer=void 0),this.mapTimer=setTimeout(()=>{this.map&&this.map.isShow&&this.map.show(),this.canvas&&this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.resize()},500)}toggleAnchorMode(){this.canvas.toggleAnchorMode()}addAnchorHand(){this.canvas.addAnchorHand()}removeAnchorHand(){this.canvas.removeAnchorHand()}toggleAnchorHand(){this.canvas.toggleAnchorHand()}top(e){e||(e=this.store.active),Array.isArray(e)||(e=[e]);for(const t of e){const i=this.store.data.pens,r=[...S1(t,this.store),t].map(a=>a.id);i.filter(a=>r.includes(a.id)).forEach(a=>{const o=i.findIndex(l=>l.id===a.id);o>-1&&(i.push(i[o]),i.splice(o,1),this.initTemplateCanvas([a]),this.initImageCanvas([a])),this.specificLayerMove(a,"top")})}this.store.emitter.emit("layer",{type:"top",pens:e})}initImageCanvas(e){this.canvas&&this.canvas.initImageCanvas(e)}initTemplateCanvas(e){this.canvas&&this.canvas.initTemplateCanvas(e)}bottom(e){e||(e=this.store.active),Array.isArray(e)||(e=[e]);for(const t of e){const i=this.store.data.pens,r=[...S1(t,this.store),t].map(a=>a.id),n=i.filter(a=>r.includes(a.id));for(let a=n.length-1;a>=0;a--){const o=n[a],l=i.findIndex(c=>c.id===o.id);l>-1&&(i.unshift(i[l]),i.splice(l+1,1),this.initTemplateCanvas([o]),this.initImageCanvas([o])),this.specificLayerMove(o,"bottom")}}this.store.emitter.emit("layer",{type:"bottom",pens:e})}upByArea(e){if(this.store.data.pens.findIndex(l=>l.id===e.id)===-1){console.warn("upByArea: pen not in canvas");return}const i=[e,...S1(e,this.store)];let r=i.map(l=>this.store.data.pens.findIndex(c=>c.id===l.id));r.includes(-1)&&(console.warn("upByArea: pen children not in canvas"),r=r.filter(l=>l!==-1));const n=Math.min(...r),a=e.calculative.worldRect,o=this.store.data.pens.findIndex((l,c)=>{if(c<=n||l.id===e.id||Tft(l,e))return!1;const u=l.calculative.worldRect;return ov(a,u)});if(o===-1){this.up(e);return}this.store.data.pens.splice(o+1,0,...i);for(const l of i){const c=this.store.data.pens.findIndex(u=>u.id===l.id);c>-1&&this.store.data.pens.splice(c,1)}this.initImageCanvas([e])}specificLayerMove(e,t){var i;if(e.image&&e.name!=="gif"){let r=hn.CanvasImageBottom;t==="top"?r=hn.CanvasImage:(t==="up"||t==="down")&&(r=hn.CanvasMain),this.setValue({id:e.id,canvasLayer:r},{render:!1,doEvent:!1,history:!1})}else if(e.externElement||e.name==="gif"){let r=0;t==="top"?(e.calculative.canvas.maxZindex+=1,r=e.calculative.canvas.maxZindex):t==="up"?r=e.calculative.zIndex===void 0?6:e.calculative.zIndex+1:t==="down"&&(r=e.calculative.zIndex===void 0?3:e.calculative.zIndex-1,r<0&&(r=0)),this.setValue({id:e.id,zIndex:r},{render:!1,doEvent:!1,history:!1}),(i=e.calculative.singleton)!=null&&i.div&&Ha(e,e.calculative.singleton.div)}}up(e){e||(e=this.store.active),Array.isArray(e)||(e=[e]);for(const t of e){const i=this.store.data.pens;if(t.children&&t.children.length){const r=[...S1(t,this.store),t],n=[];for(let l=0;lu.id===c.id)!==-1&&(c.temIndex=l,n.push(c))}let a=-1,o=0;n.forEach(l=>{l.temIndex-=o,i.splice(l.temIndex,1),o+=1,a=l.temIndex,delete l.temIndex,this.specificLayerMove(l,"up")}),i.splice(a+1,0,...n),this.initTemplateCanvas(n),this.initImageCanvas(n)}else{const r=i.findIndex(n=>n.id===t.id);r>-1&&r!==i.length-1&&(i.splice(r+2,0,i[r]),i.splice(r,1),this.initTemplateCanvas([t]),this.initImageCanvas([t])),this.specificLayerMove(t,"up")}}this.store.emitter.emit("layer",{type:"up",pens:e})}down(e){e||(e=this.store.active),Array.isArray(e)||(e=[e]);for(const t of e){const i=this.store.data.pens;if(t.children&&t.children.length){const r=[...S1(t,this.store),t],n=[];for(let l=0;lu.id===c.id)!==-1&&(c.temIndex=l,n.push(c))}let a=-1,o=0;n.forEach((l,c)=>{l.temIndex-=o,i.splice(l.temIndex,1),o+=1,c===0&&(a=l.temIndex),delete l.temIndex,this.specificLayerMove(l,"down")}),i.splice(a-1,0,...n),this.initTemplateCanvas(n),this.initImageCanvas(n)}else{const r=i.findIndex(n=>n.id===t.id);r>-1&&r!==0&&(i.splice(r-1,0,i[r]),i.splice(r+1,1),this.initTemplateCanvas([t]),this.initImageCanvas([t])),this.specificLayerMove(t,"down")}}this.store.emitter.emit("layer",{type:"down",pens:e})}setLayer(e,t,i=this.store.data.pens){const r=i.findIndex(n=>n.id===e.id);r>-1&&(r>t?(i.splice(t,0,i[r]),i.splice(r+1,1)):r{const a=this.store.pens[n];if(!a){console.warn(e,"node contain a error connectedLine");return}if(!i.find(o=>o.id===a.id))switch(t){case"all":i.push(a);break;case"in":Dn(a).connectTo===e.id&&i.push(a);break;case"out":rl(a).connectTo===e.id&&i.push(a);break}}),i}nextNode(e){if(e.type===Kn.Line){const t=this.store.pens[Dn(e).connectTo];return t?[t]:[]}else{const t=this.getLines(e,"out"),i=[];return t.forEach(r=>{const n=this.nextNode(r);for(const a of n)!i.find(l=>l.id===a.id)&&i.push(a)}),i}}previousNode(e){if(e.type===Kn.Line){const t=this.store.pens[rl(e).connectTo];return t?[t]:[]}else{const t=this.getLines(e,"in"),i=[];return t.forEach(r=>{const n=this.previousNode(r);for(const a of n)!i.find(l=>l.id===a.id)&&i.push(a)}),i}}getNext(e){var i;if(e.type===Kn.Line){console.warn("非连线节点");return}const t=[];return(i=e.connectedLines)==null||i.forEach(({lineId:r,anchor:n})=>{var l,c;const a=(l=e.anchors)==null?void 0:l.filter(u=>u.id===n)[0],o=this.findOne(r);if(o.anchors[0].connectTo==e.id){const u=o.anchors[o.anchors.length-1].connectTo;if(u){const h=this.findOne(u),d=(c=h.connectedLines)==null?void 0:c.filter(p=>p.lineId===o.id)[0],f=h.anchors.filter(p=>p.id===d.anchor)[0];t.push({from:e,fromAnchor:a,line:o,to:h,toAnchor:f})}}}),t}addAnchor(e,t,i){if(!e)return;if(e.anchors||(e.anchors=[]),e.calculative.worldAnchors||(e.calculative.worldAnchors=[]),e.type===Kn.Line&&(i<0&&(i=e.anchors.length+1+i),i>e.anchors.length&&(i=e.anchors.length),i<0&&(i=0),i==0&&e.anchors[0].connectTo||i==e.anchors.length&&e.anchors[i-1].connectTo)){console.warn("端点存在连接关系");return}let r=null,n=null;t.x<=1&&t.x>=0&&t.y<=1&&t.y>=0?(n={id:t.id||fs(),penId:e.id,x:e.calculative.worldRect.x+e.calculative.worldRect.width*t.x,y:e.calculative.worldRect.y+e.calculative.worldRect.height*t.y},e.calculative.worldRect&&e.rotate%360&&Pa(n,e.rotate,e.calculative.worldRect.center),r={id:n.id,penId:e.id,x:t.x,y:t.y}):(n={id:t.id||fs(),penId:e.id,x:t.x,y:t.y},e.calculative.worldRect&&(e.rotate%360&&Pa(t,-e.rotate,e.calculative.worldRect.center),r={id:n.id,penId:e.id,x:(t.x-e.calculative.worldRect.x)/e.calculative.worldRect.width,y:(t.y-e.calculative.worldRect.y)/e.calculative.worldRect.height})),e.type===Kn.Line?(e.calculative.worldAnchors.splice(i,0,n),e.anchors.splice(i,0,r),this.canvas.updateLines(e),this.canvas.initLineRect(e),this.render()):(e.calculative.worldAnchors.push(n),e.anchors.push(r))}connectLine(e,t,i,r,n=!0){if(!i){const c=t.calculative.worldRect;i=R5(e,{x:c.x+c.width/2,y:c.y+c.height/2})}if(!r){const c=e.calculative.worldRect;r=R5(t,{x:c.x+c.width/2,y:c.y+c.height/2})}const a=Math.abs(i.x-r.x),l={height:Math.abs(i.y-r.y),lineName:"line",lineWidth:1,name:"line",type:1,width:a,x:Math.min(i.x,r.x),y:Math.min(i.y,r.y),anchors:[{x:i.x>r.x?1:0,y:i.y>r.y?1:0,id:fs()},{x:i.x>r.x?0:1,y:i.x>r.x?0:1,id:fs()}]};return this.addPens([l]),Zc(e,i,l,l.calculative.worldAnchors[0]),Zc(t,r,l,l.calculative.worldAnchors[1]),l.calculative.active=!1,this.canvas.updateLines(l),this.canvas.updateLines(e),this.canvas.updateLines(t),this.canvas.initLineRect(l),n&&this.render(),l}toComponent(e=this.store.data.pens,t,i){if(e.length===1){const u=bt(e[0]);return u.type=Kn.Node,u.id=void 0,[u]}const r=bt(e,!0),n=Um(r);let a={id:fs(),name:"combine",...n,children:[],showChild:t};i&&(a.anchors=[{id:"0",penId:a.id,x:.5,y:0},{id:"1",penId:a.id,x:1,y:.5},{id:"2",penId:a.id,x:.5,y:1},{id:"3",penId:a.id,x:0,y:.5}]);const o=r.filter(u=>!u.parentId),l=r.find(u=>u.width===n.width&&u.height===n.height),c=l&&t===void 0;return o.length===1?a=o[0]:c&&(l.children||(l.children=[]),a=l),r.forEach(u=>{if(u===a||u.parentId===a.id||u.parentId)return;a.children.push(u.id),u.parentId=a.id;const h=yy(u.calculative.worldRect,n);Object.assign(u,h),u.locked=u.lockedOnCombine??qs.DisableMove}),c||o.length===1?bt(r):bt([a,...r])}installPenPlugins(e,t){if(!e.tag&&!e.name&&!e.id)return;let i;e.id?i="id":e.tag?i="tag":e.name&&(i="name"),t.forEach(r=>{let n=r.plugin,a=r.options;if(n&&cpt(n)&&i)if(n.install(e,a),!this.penPluginMap.has(n))this.penPluginMap.set(n,[{[i]:e[i],option:a}]);else{let o=this.penPluginMap.get(n).find(l=>l[i]===e[i]);o?o.option=a:this.penPluginMap.get(n).push({[i]:e[i],option:a})}})}uninstallPenPlugins(e,t){let i;e.id?i="id":e.tag?i="tag":e.name&&(i="name"),i&&t.forEach(r=>{let n=r.plugin;n.uninstall(e,r.options);let a=this.penPluginMap.get(n),o=a.findIndex(l=>l[i]===e[i]);o!==-1&&(a.splice(o,1),a.length===0&&this.penPluginMap.delete(n))})}setVisible(e,t,i=!0){if(this.onSizeUpdate(),this.setValue({id:e.id,visible:t},{render:!1,doEvent:!1}),e.children)for(const n of e.children){const a=this.store.pens[n];a&&this.setVisible(a,t,!1)}let r=S1(e,this.store);r.push(e),this.initImageCanvas(r),i&&this.render()}clearHover(){this.canvas.clearHover()}closeSocket(){this.closeWebsocket(),this.closeMqtt(),this.closeHttp()}destroy(e){if(this.clear(!1),this.stopDataMock(),this.closeSocket(),this.closeNetwork(),this.closeAll(),wse.destroyThemeSheet(this.store.id),this.store.emitter.all.clear(),this.canvas.destroy(),this.canvas=void 0,Lr[this.store.id]=void 0,!e){for(const t in Lr)delete Lr[t];Lr.path2dDraws={},Lr.canvasDraws={},Lr.anchors={},Lr.htmlElements={}}}}function Y0t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,ey:a}=s.calculative.worldRect,o=n/4;if(t.moveTo(i+o,r),t.lineTo(i,r),t.lineTo(i,a),t.lineTo(i+o,a),t instanceof Path2D)return t}function Q0t(s){const e=[{x:.25,y:0},{x:.25,y:1},{x:0,y:.5}];s.anchors=e.map(({x:t,y:i},r)=>({id:r+"",x:t,y:i,penId:s.id}))}function $0t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,ex:a,ey:o}=s.calculative.worldRect,l=s.offsetX;let c=n/7;if(l>1?c=l:l>0&&(c=n*l),t.moveTo(i+c,r),t.lineTo(a,r),t.lineTo(i+n-c,o),t.lineTo(i,o),t.closePath(),t instanceof Path2D)return t}function Z0t(s){const e=[{x:.5,y:0},{x:.9285714285714286,y:.5},{x:.5,y:1},{x:.07142857142857142,y:.5}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function q0t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a,ex:o,ey:l}=s.calculative.worldRect,c=n/8;if(t.moveTo(i+c,r),t.lineTo(o-c,r),t.bezierCurveTo(o+c/3,r,o+c/3,l,o-c,l),t.lineTo(i+c,l),t.lineTo(i,r+a/2),t.closePath(),t instanceof Path2D)return t}function J0t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a,ex:o,center:l}=s.calculative.worldRect,c=l.x,u=r+a*6/7,h=a/6;if(t.moveTo(i,r),t.lineTo(o,r),t.lineTo(o,u),t.bezierCurveTo(o-20,u-h,c+n/5,u-h,c,u),t.bezierCurveTo(c-n/5,u+h,i,u+h,i,u),t.closePath(),t instanceof Path2D)return t}function emt(s){const e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:.8571428571428571},{x:0,y:.5}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function tmt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,ex:a,ey:o}=s.calculative.worldRect,l=n/10;if(t.moveTo(i+l*2,r),t.bezierCurveTo(i-l*2/3,r,i-l*2/3,o,i+l*2,o),t.lineTo(a,o),t.bezierCurveTo(a-l,o,a-l,r,a,r),t.closePath(),t instanceof Path2D)return t}function imt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,ex:a,ey:o}=s.calculative.worldRect;t.moveTo(i,r),t.lineTo(a,r),t.lineTo(a,o),t.lineTo(i,o),t.closePath();const l=n/7;if(t.moveTo(i,r+l),t.lineTo(a,r+l),t.moveTo(i+l,r),t.lineTo(i+l,o),t instanceof Path2D)return t}function rmt(s,e){const t=e||new Path2D,{x:i,y:r,height:n,ex:a,ey:o}=s.calculative.worldRect,l=n/4;if(t.moveTo(i,r+l),t.lineTo(a,r),t.lineTo(a,o),t.lineTo(i,o),t.closePath(),t instanceof Path2D)return t}function smt(s){const e=[{x:.5,y:.125},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function nmt(s,e){const t=e||new Path2D,{x:i,y:r,ex:n,ey:a}=s.calculative.worldRect;if(t.moveTo(i,r),t.lineTo(n,r),t.moveTo(i,a),t.lineTo(n,a),t instanceof Path2D)return t}function amt(s){const e=[{x:.5,y:0},{x:.5,y:1}];s.anchors=e.map(({x:t,y:i},r)=>({id:r+"",x:t,y:i,penId:s.id}))}function omt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a,ex:o,ey:l}=s.calculative.worldRect;if(t.ellipse(i+n/2,r+a/2,n/2,a/2,0,0,Math.PI*2),t.moveTo(i+n/2,l),t.lineTo(o,l),t.closePath(),t instanceof Path2D)return t}function lmt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,ex:a,ey:o}=s.calculative.worldRect,l=n/7;if(t.moveTo(i,r),t.lineTo(a,r),t.lineTo(a,o),t.lineTo(i,o),t.closePath(),t.moveTo(i+l,r),t.lineTo(i+l,o),t.moveTo(a-l,r),t.lineTo(a-l,o),t instanceof Path2D)return t}function cmt(s,e){const t=e||new Path2D,{x:i,y:r,height:n,ex:a,ey:o}=s.calculative.worldRect,l=n/7;if(t.moveTo(i,r+l),t.bezierCurveTo(i,r-l/2|0,a,r-l/2|0,a,r+l),t.lineTo(a,o-l),t.bezierCurveTo(a,o+l/2|0,i,o+l/2|0,i,o-l),t.closePath(),t.moveTo(i,o-l),t.bezierCurveTo(i,o-l*2|0,a,o-l*2|0,a,o-l),t instanceof Path2D)return t}function umt(){return{flowComment:Y0t,flowData:$0t,flowDb:cmt,flowDisplay:q0t,flowDocument:J0t,flowExternStorage:tmt,flowInternalStorage:imt,flowManually:rmt,flowParallel:nmt,flowQueue:omt,flowSubprocess:lmt}}function hmt(){return{flowDocument:emt,flowManually:smt,flowParallel:amt,flowComment:Q0t,flowData:Z0t}}function dmt(s,e){const{x:t,y:i,width:r,height:n}=e.calculative.worldRect;s.beginPath(),s.ellipse(t+r/2,i+n/2,r/2,n/2,0,0,Math.PI*2),s.stroke(),s.beginPath(),s.fillStyle=s.strokeStyle,s.ellipse(t+r/2,i+n/2,r/4,n/4,0,0,Math.PI*2),s.fill()}function fmt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a,ey:o}=s.calculative.worldRect,l=s.calculative.lineLeft||.08;let c=s.calculative.borderRadius||0,u=c;c<1&&(c=n*c,u=a*c);let h=c{const i=e.data.pens.findIndex(r=>r.id===t);i>-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)}),s.children=void 0}function xmt(s,e){s.onDestroy||(s.onDestroy=bmt,s.onAdd=Amt);const t=e||new Path2D,{x:i,y:r,width:n,height:a,ex:o}=s.calculative.worldRect;let l=s.calculative.borderRadius||0,c=l;l<1&&(l=n*l,c=a*c);let u=l{const i=e.data.pens.findIndex(r=>r.id===t);i>-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)}),s.children=[]}function Cmt(){return{interfaceClass:_mt,simpleClass:xmt}}function Smt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;if(t.rect(i,r,n,a),t.closePath(),t instanceof Path2D)return t}function Emt(s,e){const t=e.headHeight??50,{x:i,y:r,width:n,height:a,ey:o}=e.calculative.worldRect;let l=e.calculative.borderRadius||0,c=l;e.calculative.borderRadius<1&&(l*=n,c*=a);let u=l{o.text().then(l=>{if(typeof l=="string")try{l=JSON.parse(l)}catch{}if(l.constructor!==Object&&l.constructor!==Array){console.warn("Invalid data:",l);return}e.registerMap(s.echarts.geoName,l),s.calculative.singleton.echartsReady=!0,s.calculative.singleton.echart.setOption(eZ(s.echarts.option,s.calculative.canvas.store.data.scale),!0),s.calculative.singleton.echart.resize(),setTimeout(()=>{kse(s)},300)})}))),s.calculative.singleton.echartsReady&&setTimeout(()=>{s.calculative.singleton.echart.setOption(eZ(s.echarts.option,s.calculative.canvas.store.data.scale),!0),setTimeout(()=>kse(s),300)})}return t}function Imt(s){var i;const e=s.calculative.singleton.echart,t=["click","dblclick","mousedown","mousemove","mouseup","mouseover","mouseout","globalout","contextmenu"];t.forEach(r=>{e.off(r)}),(i=s.events)==null||i.forEach(r=>{r.actions&&r.actions.length&&t.includes(r.name)&&e.on(r.name,n=>{let a=!1;r.conditions&&r.conditions.length?r.conditionType==="and"?a=r.conditions.every(o=>s.calculative.canvas.parent.judgeCondition(s,o.key,o)):r.conditionType==="or"&&(a=r.conditions.some(o=>s.calculative.canvas.parent.judgeCondition(s,o.key,o))):a=!0,a&&r.actions.forEach(o=>{if(o.timeout){let l=setTimeout(()=>{s.calculative.canvas.parent.events[o.action]&&(s.calculative.canvas.parent.events[o.action](s,o,n),clearTimeout(l),l=null)},o.timeout)}else s.calculative.canvas.parent.events[o.action]&&s.calculative.canvas.parent.events[o.action](s,o,n)})})})}function Pmt(s){if(s.calculative.singleton&&s.calculative.singleton.div){s.calculative.singleton.div.remove();let e=globalThis.echarts;e&&e.dispose(s.calculative.singleton.echart),delete s.calculative.singleton.div,delete s.calculative.singleton.echart}}function KQ(s){s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div)}function wmt(s){var e;KQ(s),(e=s.calculative.singleton)!=null&&e.echart&&s.calculative.singleton.echart.resize()}function Dmt(s){var t,i;if(!s.calculative.singleton.echart)return;let e=globalThis.echarts;if(Ha(s,s.calculative.singleton.div),!(s.echarts.geoName&&!e.getMap(s.echarts.geoName))){if(!s.echarts.diabled){if((t=s.echarts.option)!=null&&t.dataZoom){const n=s.calculative.singleton.echart.getOption().dataZoom;(i=s.echarts.option.dataZoom)==null||i.forEach((a,o)=>{n[o]&&(a.start=n[o].start,a.end=n[o].end)})}s.calculative.singleton.echart.setOption(eZ(s.echarts.option,s.calculative.canvas.store.data.scale),!0)}s.calculative.singleton.echart.resize()}}function Lmt(s){var e,t;if(s.calculative.singleton.echart&&(Ha(s,s.calculative.singleton.div),s.calculative.singleton.echartsReady))if(s.calculative.partialOption){const i=s.calculative.partialOption.echarts.option;(Array.isArray((e=s.echarts)==null?void 0:e.replaceMerge)?(t=s.echarts)==null?void 0:t.replaceMerge.some(n=>i[n]):!1)?s.calculative.singleton.echart.setOption(bt(i),{replaceMerge:s.echarts.replaceMerge}):s.calculative.singleton.echart.setOption(bt(i))}else s.calculative.singleton.echart.setOption(eZ(s.echarts.option,s.calculative.canvas.store.data.scale),!0)}function Omt(s,e){if(s.calculative.partialOption=null,e.echarts){let p=globalThis.echarts;return e.echarts.geoName&&!p.getMap(e.echarts.geoName)&&(e.echarts.geoJson?p.registerMap(e.echarts.geoName,e.echarts.geoJson):e.echarts.geoUrl&&(s.calculative.singleton.echartsReady=!1,fetch(e.echarts.geoUrl).then(m=>{m.text().then(g=>{if(typeof g=="string")try{g=JSON.parse(g)}catch{}if(g.constructor!==Object&&g.constructor!==Array){console.warn("Invalid data:",g);return}return p.registerMap(e.echarts.geoName,g),s.calculative.singleton.echartsReady=!0,s.onValue(s),!1})}))),e}if(s.realTimes&&s.realTimes.length){let p=Object.keys(e);const{xAxis:m,yAxis:g}=s.echarts.option,{max:_,replaceMode:y,timeFormat:v}=s.echarts;let x=[],A=!1;for(let b in e)if(b.includes("echarts.option")){A=!0;let C=oS(s,b);if(Array.isArray(C)&&y===0&&(C.push(e[b]),_&&C.splice(0,C.length-_),e[b]=C,!p.includes("echarts.option.xAxis.data"))){let T="echarts.option.xAxis.data";Array.isArray(m)&&m.length&&(T="echarts.option.xAxis.0.data");let w=oS(s,T),P=Eft(v||"`${hours}:${minutes}:${seconds}`");w.push(P),_&&w.splice(0,w.length-_),e[T]=w}if(b.includes(".data.")){let T=b.substring(0,b.indexOf(".data.")+5);x.includes(T)||x.push(T)}}if(A){const b=bt(e);s.calculative.partialOption=Fmt(b,s),x.forEach(C=>{let T=oS(s,C);Q$(s.calculative.partialOption,C,T)})}return e}if(!e.dataX&&!e.dataY)return e;const t=s.echarts,{max:i,replaceMode:r}=t;let n=e.dataX,a=e.dataY,o=[];a&&o.push("echarts.option.series");const l=t.option.series,c=l.length,{xAxis:u,yAxis:h}=t.option;Array.isArray(u)&&u.length>1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");const d=Array.isArray(u)?u[0]:u,f=Array.isArray(h)?h[0]:h;if(r)if(r===1){if(!d&&!f)a&&(c===1?(!Array.isArray(a)&&(a=[a]),a.forEach((p,m)=>{const g=l[0].data.find(_=>_.name===p.name);g&&(g.value=p.value)})):l.forEach((p,m)=>{Array.isArray(a[m])||(a[m]=[a[m]]),a[m].forEach((g,_)=>{const y=p.data.find(v=>v.name===g.name);y&&(y.value=g.value)})}));else if((d.type==="category"||f.type==="category")&&n&&a){const p=d.type==="category"?d.data:f.data;!Array.isArray(n)&&(n=[n]),!Array.isArray(a)&&(a=[a]),d.type==="category"?o.push("echarts.option.xAxis"):o.push("echarts.option.yAxis"),c===1?a.forEach((m,g)=>{const _=p.indexOf(n[g]);l[0].data[_]=m}):l.forEach((m,g)=>{a[g].forEach((_,y)=>{const v=p.indexOf(n[y]);m.data[v]=_})})}}else r===2&&(n&&(d.data=n,d.data.splice(0,d.data.length-i),o.push("echarts.option.xAxis")),a&&(c===1?(l[0].data=a,l[0].data.splice(0,l[0].data.length-i)):l.forEach((p,m)=>{p.data=a[m],p.data.splice(0,p.data.length-i)})));else{if(n){!Array.isArray(n)&&(n=[n]);const p=d.data;p.push(...n),p.splice(0,p.length-i),o.push("echarts.option.xAxis")}if(a)if(c===1){!Array.isArray(a)&&(a=[a]);const p=l[0].data;p.push(...a),p.splice(0,p.length-i)}else l.forEach((p,m)=>{Array.isArray(a[m])||(a[m]=[a[m]]);const g=p.data;g.push(...a[m]),g.splice(0,g.length-i)})}return s.calculative.partialOption={},o.forEach(p=>{let m=oS(s,p);Q$(s.calculative.partialOption,p,m)}),delete e.dataX,delete e.dataY,Object.assign(e,{echarts:t})}function Nmt(s,e,t){if(t.key!=="dataY")return;const i=s.echarts,{xAxis:r,yAxis:n}=i.option;Array.isArray(r)&&r.length>1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");const a=Array.isArray(r)?r[0]:r,o=Array.isArray(n)?n[0]:n,l=i.option.series;if(!a&&!o){const c=[];if(Array.isArray(l)&&l.length===1)return l[0].data.forEach(u=>{const{dataId:h}=t.dataIds.find(d=>d.name===u.name);if(h){const d=e.find(f=>f.dataId===h);d&&c.push({name:u.name,value:d.value})}}),{id:s.id,dataY:c}}else if(a.type==="category"||o.type==="category"){const c=[],u=[],h=a.type==="category"?a.data:o.data;return h==null||h.forEach(d=>{const{dataId:f}=t.dataIds.find(p=>p.name===d);if(f){const p=e.find(m=>m.dataId===f);p&&(u.push(d),c.push(p.value))}}),{id:s.id,dataY:c,dataX:u}}else if(a.type==="time"){const c=[],u=+new Date;let h=!1;if(l.forEach((d,f)=>{const p=[],{dataId:m}=t.dataIds.find(g=>g.name===d.name);if(m){const g=e.find(_=>_.dataId===m);g&&(p.push([u,g.value]),h=!0)}c[f]=p}),h)c.forEach((d,f)=>{if(!d||d.length===0){const p=l[f].data[l[f].data.length-1];c[f]=[[u,p[1]]]}});else return;return{id:s.id,dataY:c.length===1?c[0]:c}}}function kse(s){var t,i;const e=new Image;e.src=(i=(t=s.calculative.singleton)==null?void 0:t.echart)==null?void 0:i.getDataURL({pixelRatio:2}),s.calculative.img=e}function eZ(s,e){const t=bt(s);if(t.dataZoom){let i=["right","top","width","height","left","bottom"];for(let r=0;r{isNaN(n[i[r]])||(n[i[r]]*=e)})}return Zce(t,aue,e),t}function Fmt(s,e){const t={};return Object.keys(s).forEach(i=>{const r=i.split(".");let n=t;r.forEach((a,o)=>{const l=!isNaN(parseInt(a));if(o===6){let c=r.slice(0,7).join(".");Q$(e,i,s[i]);let u=oS(e,c);n[r[o]]=u}else{if(o>6)return;if(o===r.length-1)l?(Array.isArray(n)||(n=[]),n[parseInt(a)]=s[i]):n[a]=s[i];else if(l){const c=parseInt(a);if(Array.isArray(n)||n[r[o-1]],n[c]||(n[c]={}),Array.isArray(n))for(let u=0;u{s.calculative.singleton.highchart=e.chart(s.id,s.highcharts.option);const a=s.calculative.singleton.highchart.getSVG(),o=new Image;o.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(a))),s.calculative.img=o}),(r=s.calculative.canvas.externalElements)==null||r.parentElement.appendChild(n),Ha(s,n)}return s.calculative.patchFlags&&s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div),t}function kmt(s){s.calculative.singleton&&s.calculative.singleton.div&&(s.calculative.singleton.div.remove(),s.calculative.singleton.highchart.destroy(),delete s.calculative.singleton.div,delete s.calculative.singleton.highchart)}function SEe(s){s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div)}function Umt(s){s.calculative.singleton.div&&(Ha(s,s.calculative.singleton.div),setTimeout(()=>{s.calculative.singleton.highchart.reflow()},100))}function zmt(s){s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div)}function Vmt(s,e){if(e.highcharts)return s.calculative.singleton.highchart.update(e.highcharts.option),e;if(!e.dataX&&!e.dataY)return e;const t=s.highcharts,i=t.max;let r=e.dataX,n=e.dataY;const a=t.option.series.length;if(e.overwrite)r&&(t.option.xAxis.categories=r,t.option.xAxis.categories.splice(0,t.option.xAxis.categories.length-i)),n&&(a===1?(t.option.series[0].data=n,t.option.series[0].data.splice(0,t.option.series[0].data.length-i)):t.option.series.forEach((l,c)=>{l.data=n[c],l.data.splice(0,l.data.length-i)})),s.calculative.singleton.highchart.update(t.option);else{let o=[],l=null,c=!1;if(r){Array.isArray(r)||(r=[r]);const u=t.option.xAxis,h=Array.isArray(u)?u[0].categories:u.categories;h&&(h.push(...r),h.splice(0,h.length-i),c=!0),o=[...r]}n&&(a===1?(Array.isArray(n)||(n=[n]),l=[n]):(l=[],t.option.series.forEach((u,h)=>{Array.isArray(n[h])||(n[h]=[n[h]]),l.push(n[h])}))),l&&s.calculative.singleton.highchart.series.forEach((h,d)=>{l[d].forEach((f,p)=>{let m=!1;i&&h.data.length>=i&&(m=!0);const g=c||o[p]==null?f:[o[p],f];h.addPoint(g,!0,m)})})}return delete e.dataX,delete e.dataY,delete e.overwrite,Object.assign(e,{highcharts:t})}function Gmt(s){var i;if(!((i=s.calculative)!=null&&i.singleton))return;const e=s.calculative.singleton.highchart.getSVG(),t=new Image;t.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(e))),s.calculative.img=t}function Wmt(s){let e=globalThis.lcjs;if(!s.lightningCharts||!e)return;if(typeof s.lightningCharts=="string")try{s.lightningCharts=JSON.parse(s.lightningCharts)}catch{}if(!s.lightningCharts)return;s.onDestroy||(s.onDestroy=Hmt,s.onMove=EEe,s.onResize=jmt,s.onRotate=EEe,s.onValue=Xmt,s.onRenderPenRaw=Ymt);const t=new Path2D,i=s.calculative.worldRect;if(s.calculative.singleton||(s.calculative.singleton={}),!s.calculative.singleton.div){const r=document.createElement("div");r.style.position="absolute",r.style.outline="none",r.style.left="-9999px",r.style.top="-9999px",r.style.width=i.width+"px",r.style.height=i.height+"px",r.id=s.id,document.body.appendChild(r),s.calculative.singleton.div=r,setTimeout(()=>{lFe(s)},100),setTimeout(()=>{s.calculative.canvas.externalElements&&s.calculative.canvas.externalElements.parentElement.appendChild(r),Ha(s,r);const n=new Image;n.src=s.calculative.singleton.div.children[0].toDataURL(),s.calculative.img=n},400)}return s.calculative.patchFlags&&s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div),t}function Kmt(s){let e=s.toLowerCase();const t=/^#([0-9|a-f]{3}|[0-9|a-f]{6})$/,i=/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;if(e&&t.test(e)){e.length==4&&(e="#"+e[1]+e[1]+e[2]+e[2]+e[3]+e[3]);for(var r=[],n=1;n<7;n+=2)r.push(parseInt("0x"+e.slice(n,n+2)));return r}else if(e&&i.test(e))return e.match(/\(([^)]*)\)/)[1].split(",").map(l=>parseInt(l));return e}function lFe(s){const{lightningChart:e,PieChartTypes:t,LegendBoxBuilders:i,SliceLabelFormatters:r,Themes:n,GaugeChartTypes:a,SolidLine:o,SolidFill:l,ColorRGBA:c,UIOrigins:u,emptyLine:h,AutoCursorModes:d,AxisScrollStrategies:f,AxisTickStrategies:p,UIElementBuilders:m}=lcjs,g=s.lightningCharts.option.data,_=s.lightningCharts.option.title||"Title",y=n[s.lightningCharts.option.theme||"lightNew"];switch(s.calculative.singleton.lightningChart=e(),s.lightningCharts.option.type){case"line":const v=s.calculative.singleton.lightningChart.ChartXY({container:s.id}).setTitle(_);g.forEach(M=>{v.addLineSeries().setName(M.name).add(M.data)});break;case"bar":const x=s.calculative.singleton.lightningChart;let A;A=M=>{const k=[],V=[],H=x.ChartXY(M).setTitle(_).setAutoCursorMode(d.onHover).setMouseInteractions(!1).setPadding({bottom:30}),j=H.getDefaultAxisX().setMouseInteractions(!1).setScrollStrategy(void 0).setTickStrategy(p.Empty);H.getDefaultAxisY().setMouseInteractions(!1).setTitle(s.lightningCharts.option.yTitle).setInterval(0,70).setScrollStrategy(f.fitting),H.setAutoCursor(q=>q.disposePointMarker().disposeTickMarkerX().disposeTickMarkerY().setGridStrokeXStyle(h).setGridStrokeYStyle(h).setResultTable(ie=>{ie.setOrigin(u.CenterBottom)}));const z=q=>{const ie=H.addRectangleSeries();return ie.setCursorResultTableFormatter((ae,ue,ce)=>{let N={name:q.name,value:q.data[q.figures.indexOf(ce)]};return ae.addRow("Department:",N.name).addRow("# of employees:",String(N.value))}),ie},K=H.addLegendBox(i.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.2}),U=()=>{let q=0;for(let ie=0;ie{const ie=z(q).setName(q.name);q.figures=q.data.map(ae=>ie.add({x:0,y:0,width:0,height:0})),K.add(ie),V.push(q),U()},addGroups:q=>{for(const ie of q)k.push({name:ie,tick:j.addCustomTick(m.AxisTick).setGridStrokeLength(0).setTextFormatter(ae=>ie)})}}};const b=A({theme:y,container:s.id});b.addGroups(s.lightningCharts.option.groups);const C=s.lightningCharts.option.categories;g.forEach((M,R)=>b.addCategory({name:C[R],data:M}));break;case"pie":const T=s.calculative.singleton.lightningChart.Pie({theme:y,container:s.id}).setTitle(_).setAnimationsEnabled(!0).setMultipleSliceExplosion(!0);g.map(M=>T.addSlice(M.name,M.value)),T.setInnerRadius(s.lightningCharts.option.innerRadius||0).setLabelFormatter(r.NamePlusRelativeValue),T.addLegendBox(i.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.3}).add(T);break;case"gauge":const w=s.calculative.singleton.lightningChart.Gauge({theme:y,container:s.id}).setTitle(_).setThickness(20).setAngleInterval(s.lightningCharts.option.startAngle||225,s.lightningCharts.option.endAngle||-45);let P=Kmt(s.lightningCharts.option.background);w.getDefaultSlice().setInterval(s.lightningCharts.option.min||0,s.lightningCharts.option.max||100).setValue(g).setFillStyle(new l({color:c(P[0],P[1],P[2])}));break}}function Hmt(s){s.calculative.singleton&&s.calculative.singleton.div&&(s.calculative.singleton.div.remove(),delete s.calculative.singleton.div,delete s.calculative.singleton.lightningChart)}function EEe(s){s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div)}function jmt(s){s.calculative.singleton.div&&Ha(s,s.calculative.singleton.div)}function Xmt(s){s.calculative.singleton.div&&(lFe(s),Ha(s,s.calculative.singleton.div))}function Ymt(s){var t;if(!((t=s.calculative)!=null&&t.singleton))return;const e=new Image;e.src=s.calculative.singleton.div.children[0].toDataURL(),s.calculative.img=e}function Qmt(s){R1({echarts:Rmt})}function $mt(s){R1({highcharts:Bmt})}function Zmt(s){R1({lightningCharts:Wmt})}var oue=(s=>(s[s.Add=0]="Add",s[s.Replace=1]="Replace",s[s.ReplaceAll=2]="ReplaceAll",s))(oue||{});function cFe(s,e){const t=e.calculative.worldRect.height*14/16,r=(s.match(/[\u4e00-\u9fa5]/g)||"").length;return(s.length-r)*t*.6+r*t}function uFe(s){if(s.direction=="horizontal"){const e=[];let t=0;const i=s.height;s.checkboxHeight=i,s.options.forEach((n,a)=>{e.push(a*(40+i)+t),t+=cFe(n.text,s)}),s.optionPos=e;const r=e.length*(40+i)+t;s.checkboxWidth=r,s.width=r,s.calculative.width=r,s.calculative.worldRect={x:s.x,y:s.y,height:s.height,width:s.width,center:{x:s.x+s.width/2,y:s.y+s.height/2}},Go(s.calculative.worldRect)}else if(s.direction=="vertical"){s.optionInterval==null&&(s.optionInterval=20),s.optionHeight||(s.optionHeight=20);const e=[];s.options.forEach((i,r)=>{e.push(r*(s.optionInterval+s.optionHeight))}),s.optionPos=e;const t=e[e.length-1]+s.optionHeight;s.checkboxHeight=t,s.width||(s.height=t,s.calculative.height=t,s.calculative.worldRect={x:s.x,y:s.y,height:s.height,width:s.width,center:{x:s.x+s.width/2,y:s.y+s.height/2}},Go(s.calculative.worldRect))}}function TEe(s,e){e.onAdd||(e.onAdd=hFe,(!e.rowPos||!e.colPos||!e.calculative.maxOffsetY)&&e.onAdd(e),e.onMouseMove=sgt,e.onMouseLeave=ngt,e.onMouseDown=agt,e.onShowInput=igt,e.onInput=rgt,e.onValue=cgt,e.onBeforeValue=ugt,e.onMouseEnter=mgt,e.onWheel=hgt,e.onDestroy=fgt),e.data.length!==e.rowPos.length&&(e.initWorldRect=null,e.calculative.isUpdateData=!0,e.onValue(e)),e.data[0].length!==e.colPos.length&&(e.initWorldRect=null,e.calculative.isUpdateData=!0,e.onValue(e));const t=e.calculative.canvas.store;if(e.calculative.canvas.store.data,e.calculative.canvas.store.options,e.color=e.color||t.styles.color,e.textColor=e.textColor||e.color||t.styles.textColor,e.activeColor=e.activeColor||t.styles.activeColor,e.hoverColor=e.hoverColor||t.styles.hoverColor,e.activeBackground=e.activeBackground||t.styles.activeBackground,e.hoverBackground=e.hoverBackground||t.styles.hoverBackground,!e.hasHeader){s.save(),s.beginPath();const{x:i,y:r,width:n,height:a}=e.calculative.worldRect;s.fillStyle="#fff0",s.rect(i-1,r-1,n+2,a+2),s.fill(),s.clip()}egt(s,e),tgt(s,e),qmt(s,e),s.restore(),e.isFirstTime=!1}function qmt(s,e){if(!e.calculative.hover||!e.calculative.hoverCell||e.calculative.isInput||!e.calculative.isHover)return;let t=e.calculative.worldRect,i=e.calculative.canvas.mousePos;if(!(i.x>t.x&&i.xt.y&&i.yf.col!==void 0&&f.row===void 0&&f.width);let a={};n&&n.forEach(f=>{a[f.col]=f.width});for(let f=0;fm.col===f&&m.row===void 0);p&&(i[f]=p[0])}let o=0;const l=s.styles&&s.styles.filter(f=>f.col===void 0&&f.row!==void 0&&f.height);let c={};l&&l.forEach(f=>{c[f.row]=f.height});let u=o;for(let f=0;fe.calculative.worldRect.height)continue}else if(f<0||f>e.calculative.worldRect.height)continue;s.beginPath(),s.moveTo(e.calculative.worldRect.x,e.calculative.worldRect.y+f),s.lineTo(e.calculative.worldRect.ex,e.calculative.worldRect.y+f),s.strokeStyle=e.borderColor||"#424B61",s.stroke()}}if(e.vLine!==!1){let h=e.colPos[e.colPos.length-1];e.colPos.forEach((d,f)=>{if(d===h)return;const p=d*e.calculative.worldRect.width/e.tableWidth;s.beginPath(),s.moveTo(e.calculative.worldRect.x+p,e.calculative.worldRect.y),s.lineTo(e.calculative.worldRect.x+p,e.calculative.worldRect.ey),s.strokeStyle=e.borderColor||"#424B61",s.stroke()})}s.restore()}function tgt(s,e){var i,r,n,a,o;if(!e.colPos)return;e.calculative.texts||(e.calculative.texts=[]);const t=1;for(let l=0;l0){let T=0;d.forEach((w,P)=>{w.wheres&&w.wheres.every(R=>new Function("attr",`return attr ${R.comparison} ${R.value}`)(h))&&(T=P)}),d=d[T]}else d.wheres&&Array.isArray(d.wheres)&&(f=!1,f=d.wheres.every(function(T){return new Function("attr",`return attr ${T.comparison} ${T.value}`)(h)}));let p=e.color,m=e.textColor||e.color,g=null,_=null,y=null,v=null;f&&(p=d.color||c.color||e.color,m=d.textColor||c.textColor||e.textColor,g=d.background||c.background,_=(d.fontSize||c.fontSize||0)*e.calculative.canvas.store.data.scale,y=d.fontWeight||c.fontWeight,v=d.fontStyle||c.fontStyle);let x;e.stripe&&(e.hasHeader!==!1?l%2===1&&(g=g||e.stripeColor||"#407FFF1F"):l%2===0&&(g=g||e.stripeColor||"#407FFF1F")),e.calculative.active&&((i=e.calculative.activeCell)==null?void 0:i.row)===l&&((r=e.calculative.activeCell)==null?void 0:r.col)===u&&(p=e.activeColor,g=e.activeBackground,x=p,m=e.activeTextColor||e.activeColor),e.calculative.hover&&((n=e.calculative.hoverCell)==null?void 0:n.row)===l&&((a=e.calculative.hoverCell)==null?void 0:a.col)===u&&(p=e.hoverColor,g=e.hoverBackground,m=e.hoverTextColor||e.hoverColor,x=p);const A=mFe(e,l,u);if(A.y+A.heighte.calculative.worldRect.height+e.calculative.worldRect.y)continue;g&&(s.save(),s.beginPath(),s.fillStyle=g,s.fillRect(A.x,A.y,A.width+.25*e.calculative.canvas.store.data.scale,A.height),s.restore()),x&&(s.save(),s.beginPath(),s.strokeStyle=x,s.strokeRect(A.x,A.y,A.width,A.height),s.restore()),e.calculative.worldTextRect=A;let b=e.calculative.texts[l];if(e.calculative.texts[l]||(b=[],e.calculative.texts.push(b)),b[u]==null){if(typeof h=="object"){const T=e.styles&&e.styles.filter(w=>w.col===u&&w.row===void 0&&w.pens);if(T.length>0){if(b[u]="",e.isFirstTime){e.maxNum&&e.hasHeader&&l>=e.maxNum&&(h.visible=!1);let w=JSON.parse(JSON.stringify(T[0].pens));w.forEach(P=>{Object.assign(P,{row:l,col:u},h),P.activeBackground=P.background,P.hoverBackground=P.background,P.activeColor=P.color,P.hoverColor=P.color,P.activeTextColor=P.textColor,P.hoverTextColor=P.textColor,P.height*=e.calculative.canvas.store.data.scale,P.width*=e.calculative.canvas.store.data.scale}),lgt(e,A,w),e.calculative.canvas.parent.pushChildren(e,w)}continue}}else h===void 0?b[u]="":b[u]=h.text||h+"";if(!b[u])continue;b[u]=iz(e,b[u])}if(!b[u])continue;s.save(),s.beginPath(),s.fillStyle=m,s.textAlign="center",s.textBaseline="middle",s.font=(v||e.calculative.fontStyle||"")+" normal "+(y||e.calculative.fontWeight||"")+" "+(_||e.calculative.fontSize||12)*t+"px "+e.calculative.fontFamily;let C=e.colStyle&&((o=e.colStyle[u])==null?void 0:o.textAlign);if(C&&(s.textAlign=C),b[u].length===1)C==="left"?s.fillText(b[u][0],A.x,A.y+A.height/2):C==="right"?s.fillText(b[u][0],A.x+A.width,A.y+A.height/2):s.fillText(b[u][0],A.x+A.width/2,A.y+A.height/2);else{const w=(_||e.calculative.fontSize)*e.calculative.lineHeight*t,P=b[u].length*w;let M=(A.height-P)/2;C==="left"?b[u].forEach((R,I)=>{s.fillText(R,A.x,A.y+M+(I+.55)*w)}):C==="right"?b[u].forEach((R,I)=>{s.fillText(R,A.x+A.width,A.y+M+(I+.55)*w)}):b[u].forEach((R,I)=>{s.fillText(R,A.x+A.width/2,A.y+M+(I+.55)*w)})}s.restore()}}}function hFe(s){var e;Hme(s),(e=s.children)!=null&&e.length||(s.isFirstTime=!0),s.offsetY||(s.offsetY=0),Jmt(s)}function igt(s,e){if(!s.calculative.hoverCell)return;const{value:t}=fFe(s,s.calculative.hoverCell.row,s.calculative.hoverCell.col);if(typeof t=="object")return;s.calculative.isHover=!1,s.calculative.isInput=!0,s.calculative.canvas.render(),s.calculative.inputCell=s.calculative.hoverCell;const i=mFe(s,s.calculative.hoverCell.row,s.calculative.hoverCell.col);s.calculative.tempText=t.text||t+"",s.calculative.canvas.showInput(s,i,"#ffffff")}function rgt(s,e){s.calculative.inputCell&&(pFe(s,s.calculative.inputCell.row,s.calculative.inputCell.col,e),s.calculative.isInput=!1,s.calculative.isHover=!0,s.calculative.canvas.render())}function sgt(s,e){s.timer&&(s.calculative.isHover=!1,clearTimeout(s.timer)),s.timer=setTimeout(()=>{s.calculative.isHover=!0,s.calculative.canvas.render()},500),s.calculative.hoverCell=dFe(s,e),s.calculative.canvas.render()}function ngt(s,e){Hme(s),s.calculative.hoverCell=void 0,s.calculative.canvas.render()}function agt(s,e){s.calculative.activeCell=dFe(s,e),s.calculative.canvas.render()}function dFe(s,e){const t=s.calculative.worldRect.width/s.tableWidth,i=s.calculative.worldRect.height/s.tableHeight,r={row:0,col:0};for(let n=0;ns.calculative.worldRect.x+s.colPos[n]*t&&(r.col=n+1);for(let n=0;ns.calculative.worldRect.y+s.rowPos[n]*i-s.offsetY*s.calculative.canvas.store.data.scale&&(r.row=n+1);return r}function fFe(s,e,t){if(!s.data||!Array.isArray(s.data))return;const i=s.data[e],r=s.styles&&s.styles.filter(n=>n.row===e&&n.col===t);if(Array.isArray(i))return{value:i[t],style:(r==null?void 0:r.length)>0?r.length>1?r:r[0]:{}};if(!i.data||!Array.isArray(i.data))return}function ogt(s,e){if(!s.data||!Array.isArray(s.data))return;const t=s.data[e],i=s.styles&&s.styles.filter(r=>r.row===e&&r.col===void 0);if(Array.isArray(t))return{value:t,style:(i==null?void 0:i.length)>0?i[0]:{}};if(!t.data||!Array.isArray(t.data))return}function pFe(s,e,t,i){if(!s.data||!Array.isArray(s.data))return;s.isFirstTime=!1,s.calculative.texts=void 0;let r=s.data[e];r&&(r[t]instanceof Object||(r[t]=i),s.calculative.canvas.store.emitter.emit("valueUpdate",s))}function mFe(s,e,t){const i=s.calculative.worldRect.width/s.tableWidth,r=s.calculative.worldRect.height/s.tableHeight;let n=0,a=s.colPos[t]*i;t>0&&(n=s.colPos[t-1]*i);let o=0,l=s.rowPos[e]*r;e>0&&(o=s.rowPos[e-1]*r);let c=s.offsetY*s.calculative.canvas.store.data.scale;return e===0&&s.hasHeader&&(c=0),{x:s.calculative.worldRect.x+n,y:s.calculative.worldRect.y+o-c,ex:s.calculative.worldRect.x+a,ey:s.calculative.worldRect.y+l-c,width:a-n,height:l-o}}function lgt(s,e,t){if(!(t&&t.length))return;const i=s.calculative.worldRect.width/s.tableWidth,r=s.calculative.worldRect.height/s.tableHeight;let n=1,a=1;s.initWorldRect&&(s.calculative.worldRect.width!==s.initWorldRect.width&&(n=s.calculative.worldRect.width/s.initWorldRect.width),s.calculative.worldRect.height!==s.initWorldRect.height&&(a=s.calculative.worldRect.height/s.initWorldRect.height));let o=0,l=0,c=0;const u=s.calculative.canvas.store.data.scale;if(t.length>1){for(const h of t)l+h.width*i+20*u*i{h.width=h.width*n,h.height=h.height*a})}function cgt(s){if(s.calculative.isUpdateData){delete s.calculative.isUpdateData;let e=bt(s.children);s.children=[],hFe(s),e&&e.forEach(t=>{s.calculative.canvas.delForce(s.calculative.canvas.findOne(t))}),s.calculative.texts=void 0}}function ugt(s,e){if(s.calculative.isUpdateData=!1,s.swiper!==void 0&&(s.swiper?Hme(s):Kme(s)),e.styles&&(s.initWorldRect=void 0),e.table||e.col==null&&e.row==null){if(e.dataY){const i=s.replaceMode;let r=[];return i?i===oue.Replace?(r=s.data,e.dataX&&e.dataX.forEach((n,a)=>{r[n]=e.dataY[a]})):i===oue.ReplaceAll&&(e.dataX?r[0]=e.dataX:r[0]=s.data[0],r=r.concat(e.dataY)):r=s.data.concat(e.dataY),delete e.dataX,delete e.dataY,s.calculative.isUpdateData=!0,Object.assign(e,{data:r})}(e.data||e.styles||e.maxNum||e.rowHeight||e.colWidth)&&(s.calculative.isUpdateData=!0,s.initWorldRect=null);for(let i of Object.keys(e))i.includes("data.")&&(s.calculative.isUpdateData=!0);return e}let t=s.data[e.row];return t&&(t[e.col]instanceof Object||(t[e.col]=e.value),pFe(s,e.row,e.col,e.value),s.calculative.canvas.render(),delete e.col,delete e.row),e}function hgt(s,e){if(!s.locked&&!s.calculative.canvas.store.data.locked||!s.maxNum)return;let t=0;e.deltaY>0?t=4:t=-4,lue(s,t)}function lue(s,e){var t;s.offsetY||(s.offsetY=0),s.offsetY+=e,s.offsetY>s.calculative.maxOffsetY&&(s.offsetY=s.calculative.maxOffsetY),s.offsetY<0&&(s.offsetY=0),(t=s.children)==null||t.forEach(i=>{const r=s.calculative.canvas.store.pens[i];dgt(s,r)}),s.calculative.canvas.render()}function dgt(s,e){if(!e)return;e.oldY||(e.oldY=e.y),e.calculative.worldRect,s.calculative.worldRect;const t=s.calculative.canvas.store.data.scale;s.calculative.worldRect.height/s.tableHeight;const i=s.rowHeight;e.y=e.oldY-s.offsetY*t/s.calculative.worldRect.height;const r=i*(s.initScale||1)/s.tableHeight*s.maxNum;if(s.calculative.canvas.updatePenRect(e),s.hasHeader)if(e.y1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=r;let n=e.row-s.maxNum;if(!s.data[n])return;let a=bt(s.data[n][e.col]);a.background&&(a.activeBackground=a.background,a.hoverBackground=a.background),a.color&&(a.hoverColor=a.color,a.activeColor=a.color),a.textColor&&(a.activeTextColor=a.textColor,a.hoverTextColor=a.textColor),Object.assign(e,a,{row:n}),Object.assign(e.calculative,a,{row:n})}}else e.visible=!0,e.calculative.visible=!0;else if(e.y<0){if(e.calculative.visible=!1,e.visible=!1,e.y<-i/s.tableHeight/2){e.oldY+=r;let n=e.row+s.maxNum;if(!s.data[n])return;let a=bt(s.data[n][e.col]);a.background&&(a.activeBackground=a.background,a.hoverBackground=a.background),a.color&&(a.hoverColor=a.color,a.activeColor=a.color),a.textColor&&(a.activeTextColor=a.textColor,a.hoverTextColor=a.textColor),Object.assign(e,a,{row:n}),Object.assign(e.calculative,a,{row:n})}}else if(e.y+e.height>1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=r;let n=e.row-s.maxNum;if(!s.data[n])return;let a=bt(s.data[n][e.col]);a.background&&(a.activeBackground=a.background,a.hoverBackground=a.background),a.color&&(a.hoverColor=a.color,a.activeColor=a.color),a.textColor&&(a.activeTextColor=a.textColor,a.hoverTextColor=a.textColor),Object.assign(e,a,{row:n}),Object.assign(e.calculative,a,{row:n})}}else e.calculative.visible=!0,e.visible=!0}function fgt(s){Kme(s)}function Kme(s){s.interval&&(globalThis.clearInterval(s.interval),s.interval=null)}function Hme(s){if(s.maxNum&&s.swiper){if(s.interval)return;s.interval=globalThis.setInterval(()=>{s.offsetY>=s.calculative.maxOffsetY?(s.offsetY=0,pgt(s)):s.offsetY%s.rowHeight?lue(s,1):(s.calculative.stap||(s.calculative.stap=0),s.calculative.stap+=1,s.calculative.stap==12&&(s.calculative.stap=0,lue(s,1)))},50)}}function pgt(s){var e;(e=s.children)==null||e.forEach(t=>{const i=s.rowHeight,r=s.calculative.canvas.store.pens[t];if(!r)return;const n=i*(s.initScale||1)/s.tableHeight*s.maxNum;r.oldY-=n;const a=r.row-s.maxNum;if(!s.data[a])return;let o=bt(s.data[a][r.col]);o.background&&(o.activeBackground=o.background,o.hoverBackground=o.background),o.color&&(o.hoverColor=o.color,o.activeColor=o.color),o.textColor&&(o.activeTextColor=o.textColor,o.hoverTextColor=o.textColor),r.calculative.visible=!0,r.visible=!0,Object.assign(r,o,{row:a}),Object.assign(r.calculative,o,{row:a})}),s.calculative.canvas.render()}function mgt(s){Kme(s)}function ggt(s,e){e.onClick||(e.onClick=_gt);let t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.width,n=e.calculative.worldRect.height;r2?n/2-2:1,0,Math.PI*2),s.fill()):(s.fillStyle=e.offColor,(e.disabled||e.disable)&&(s.fillStyle=e.disableOffColor||Du(.6,e.offColor)),e.lineWidth&&(s.strokeStyle=e.offStrokeColor,s.stroke()),s.fill(),s.closePath(),s.beginPath(),s.fillStyle="#ffffff",s.moveTo(t+n,i+n/2),s.arc(t+n/2,i+n/2,n/2>2?n/2-2:1,0,Math.PI*2),s.fill()),s.closePath()}function _gt(s){s.disabled||s.disable||(s.checked=!s.checked,s.calculative.canvas.store.emitter.emit("valueUpdate",s),s.calculative.canvas.render())}function vgt(s,e){e.onAdd||(e.onAdd=mB,e.onResize=mB,e.onMove=mB,e.onMouseMove=ygt,e.onMouseDown=gFe,e.onValue=xgt,e.onBeforeValue=Agt),e.calculative.barRect||mB(e);const t=e.calculative.canvas.store;e.calculative.canvas.store.options;let i=e.background;e.disabled&&(i=e.disabledBackground||Du(.6,i)),s.fillStyle=i,s.beginPath();let r=e.calculative.worldRect.x+e.calculative.barRect.x,n=e.calculative.worldRect.y+e.calculative.barRect.y,a=e.calculative.barRect.width,o=e.calculative.barRect.height,l=o/2;s.moveTo(r+l,n),s.arcTo(r+a,n,r+a,n+o,l),s.arcTo(r+a,n+o,r,n+o,l),s.arcTo(r,n+o,e.x,e.y,l),s.arcTo(r,n,r+a,n,l),s.fill();let c=e.activeColor||t.styles.activeColor;e.disabled&&(c=e.disabledColor||Du(.6,c)),s.fillStyle=c,s.beginPath(),a=e.calculative.ballRect.x,s.moveTo(r+l,n),s.arcTo(r+a,n,r+a,n+o,l),s.arcTo(r+a,n+o,r,n+o,l),s.arcTo(r,n+o,e.x,e.y,l),s.arcTo(r,n,r+a,n,l),s.fill(),s.fillStyle=e.btnBackground||"#fff",s.strokeStyle=c,s.lineWidth=2,s.beginPath(),r=e.calculative.worldRect.x+e.calculative.ballRect.x,n=e.calculative.worldRect.y+e.calculative.ballRect.y+e.calculative.ballRect.height/2,s.lineWidth=e.calculative.ballRect.width/10,s.arc(r,n,e.calculative.ballRect.width/2,0,Math.PI*2),s.fill(),s.stroke()}function mB(s){if(s._textWidth||(s._textWidth=s.textWidth||50,s._fontSize=s.fontSize||12),s.textWidth=s.calculative.worldRect.width,s.calculative.textWidth=s.textWidth,s.unit||(s.unit="%"),s.sliderWidth||(s.sliderWidth=s.width),s.sliderHeight||(s.sliderHeight=s.height),!s.calculative.worldRect)return;const e=s.calculative.worldRect.width/s.sliderWidth,t=s.calculative.worldRect.height/s.sliderHeight,i=Math.min(e,t);s.fontSize=s._fontSize*i;const r=s.calculative.worldRect.width-s._textWidth*i;s.textLeft=r+10*i,s.calculative.textLeft=s.textLeft,s.calculative.barRect={x:0,y:(s.calculative.worldRect.height-s.barHeight*t)/2,width:r,height:s.barHeight*t},Go(s.calculative.barRect),jme(s)}function jme(s){const e=s.calculative.barRect.height*3.5,t=s.calculative.barRect.width*s.value/100;s.calculative.ballRect={x:t,y:(s.calculative.worldRect.height-e)/2,width:e,height:e},Go(s.calculative.ballRect),s.calculative.text=s.value+s.unit,L1(s)}function gFe(s,e){if(s.disabled)return;const t=e.x-s.calculative.worldRect.x;if(t>s.calculative.barRect.width)return;let i=Math.round(t/s.calculative.barRect.width*100);is.max||i<0||i>100||(s.value=i,jme(s),s.calculative.text=s.value+s.unit,L1(s),s.calculative.canvas.store.emitter.emit("valueUpdate",s),s.calculative.canvas.render())}function ygt(s,e){s.calculative.canvas.mouseDown&&gFe(s,e)}function xgt(s){s.calculative.isUpdateData&&(delete s.calculative.isUpdateData,mB(s)),jme(s)}function Agt(s,e){return s.calculative.isUpdateData=!1,(e.textWidth||e.barHeight)&&(e.textWidth&&(s._textWidth=0),s.calculative.isUpdateData=!0),e}function bgt(s,e){e.onMouseDown||(e.onMouseDown=Cgt),e.options||(e.options=e.data);let t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.height;e.calculative.worldRect.width;const{fontStyle:n,fontWeight:a,fontSize:o,fontFamily:l,lineHeight:c}=e.calculative;let u=2;s.beginPath(),s.moveTo(t,i),s.arcTo(t+r,i,t+r,i+r,u),s.arcTo(t+r,i+r,t,i+r,u),s.arcTo(t,i+r,t,i,u),s.arcTo(t,i,t+r,i,u),s.strokeStyle="#d9d9d9",s.fillStyle="#ffffff00",e.checked&&(s.fillStyle=e.background||"#1890ff",s.strokeStyle=e.background||"#1890ff"),(e.isForbidden||e.disabled)&&(s.fillStyle=e.disabledBackground||Du(.6,e.background)||"#ebebeb",s.strokeStyle=e.disabledColor||Du(.6,e.color)||"#d9d9d9"),s.closePath(),s.fill(),s.stroke(),s.save(),e.checked&&(s.beginPath(),s.lineWidth=r/10,s.strokeStyle="#ffffff",s.moveTo(t+102/506*r,i+r/2),s.lineTo(t+220/506*r,i+346/460*r),s.lineTo(t+404/506*r,i+142/460*r),s.stroke()),s.restore(),s.save(),s.fillStyle=e.disabled||e.isForbidden?e.disabledTextColor||Du(.6,e.textColor||e.color)||"#00000040":Ax(e,e.calculative.canvas.parent.store)||"#000000d9",s.textAlign="start",s.textBaseline="middle",s.font=rp({fontStyle:n,fontWeight:a,fontFamily:l||e.calculative.canvas.parent.store.options.fontFamily,fontSize:o,lineHeight:c}),s.fillText(e.value+"",t+r+10,i+r/2),s.restore()}function Cgt(s,e){s.isForbidden||(s.checked=!s.checked,s.calculative.canvas.store.emitter.emit("valueUpdate",s),s.calculative.canvas.render())}function Sgt(s,e){e.options||(e.options=e.data),e.onAdd||(e.onAdd=Egt,e.optionPos||(e.onAdd(e),e.calculative.canvas.parent.active([e])),e.onMouseDown=Tgt,e.onValue=Mgt);let t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.height,n=e.calculative.worldRect.width;if(!e.optionPos)return;const{fontStyle:a,fontWeight:o,fontSize:l,fontFamily:c,lineHeight:u}=e.calculative;if(e.direction=="horizontal")for(let h=0;hs.calculative.worldRect.x+s.optionPos[t]*s.calculative.worldRect.width/s.checkboxWidth&&e.xs.calculative.worldRect.y+s.optionPos[i]*t&&e.y{const e=Igt(s);s.calculative.canvas.parent.setValue({id:s.id,text:e},{history:!1,doEvent:!1,render:!1}),s.calculative.canvas.render()},s.timeout||1e3)}function wgt(s){s.interval&&(clearInterval(s.interval),s.interval=void 0)}function Dgt(){return{radio:Sgt,switch:ggt,slider:vgt,checkbox:bgt,table:TEe,table2:TEe}}function Lgt(){return{time:Rgt}}const Ogt=15;function pC(s,e=Ogt){let t=""+s;return t.indexOf(".")>=0&&(t=Number.parseFloat(t).toFixed(e)),Number.parseFloat(t)}function Use(s){return typeof s=="number"&&Number.isFinite(s)}function Ngt(s){s={max:null,min:null,splitNumber:4,symmetrical:!1,deviation:!1,preferZero:!1,...s};const e=[10,15,20,25,30,40,50,60,70,80,90,100,150];let{max:t,min:i,splitNumber:r,symmetrical:n,deviation:a,preferZero:o}=s;if(!Use(t)||!Use(i)||t0&&(t<0?t=0:i=0);const l=(t-i)/r;let c=Math.floor(Math.log10(l)-1);c=Math.pow(10,c);const u=l/c;let h=e[0]*c,d=-1,f;for(f=0;fu){h=e[f]*c;break}let p=t,m=i;function g(y){if(p=parseInt(""+(t/y+1))*y,m=parseInt(""+(i/y-1))*y,t===0&&(p=0),i===0&&(m=0),n&&p*m<0){const v=Math.max(Math.abs(p),Math.abs(m));p=v,m=-v}}if(g(h),a)return{max:pC(p),min:pC(m),interval:pC(h),splitNumber:Math.round((p-m)/h)};if(!n||p*m>0){let y;e:do{if(y=Math.round((p-m)/h),(f-d)*(y-r)<0){for(;y=e.length-1||f<=0||y===r)break;d=f,y>r?h=e[++f]*c:h=e[--f]*c,g(h)}while(y!==r)}p=pC(p),m=pC(m);const _=pC((p-m)/r);return{max:p,min:m,interval:_,splitNumber:r}}function _Fe(s,e){var g,_,y,v,x,A,b,C,T,w,P,M,R,I,L,k,V,H,j,z,K,U,W,Z,q,ie,ae,ue;const t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,r=e.calculative.worldRect.width,n=e.calculative.worldRect.height;let a=e.calculative.canvas.store.data.scale,o=[];if(e.echarts)for(let ce=0;ce(s[s.Add=0]="Add",s[s.Replace=1]="Replace",s[s.ReplaceAll=2]="ReplaceAll",s))(Lk||{});function Bgt(s,e){e.onBeforeValue||(e.onBeforeValue=vFe);const t=e.calculative.worldRect.x,i=e.calculative.worldRect.y;e.calculative.worldRect.width;const r=e.calculative.worldRect.height;let n=e.calculative.canvas.store.data.scale,a=[];e.echarts&&!e.echarts.option.color&&(e.echarts.option.color=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]);let o=_Fe(s,e),l=o.dash,c=o.normalizedOption;const u=!!(e.echarts?e.echarts.option.series[0].smooth:e.smooth);let h=[];if(e.echarts)for(let d=0;d{p=t+(1+l/2)+(l+1)*A,m=i+r-(f[A]-c.min)/(c.max-c.min)*r;let b=t+(1+l/2)+(l+1)*(A+1),C=i+r-(f[A+1]-c.min)/(c.max-c.min)*r,T=t+(1+l/2)+(l+1)*(A-1),w=i+r-(f[A-1]-c.min)/(c.max-c.min)*r,P=t+(1+l/2)+(l+1)*(A+2),M=i+r-(f[A+2]-c.min)/(c.max-c.min)*r;A===0?(T=t+(1+l/2)+(l+1)*A,w=i+r-(f[A]-c.min)/(c.max-c.min)*r):A===f.length-2&&(P=t+(1+l/2)+(l+1)*(A+1),M=i+r-(f[A+1]-c.min)/(c.max-c.min)*r),h.push({x:p,y:m}),g=p+(b-T)/4,_=m+(C-w)/4,y=b-(P-p)/4,v=C-(M-m)/4,s.bezierCurveTo(g,_,y,v,b,C)})}else for(let g=1;g{s.beginPath(),s.strokeStyle="#fff",s.lineWidth=2*n,s.arc(g.x,g.y,4*n,0,Math.PI*2),s.stroke(),s.fill(),s.closePath()}),s.restore(),h=[]}}function vFe(s,e){if(e.xAxisData||e.data||!e.dataX&&!e.dataY)return e;const t=s.xAxisData,i=s.data,r=s.replaceMode;let n=[],a=[];return r?r===Lk.Replace?(e.dataX.forEach((o,l)=>{let c=t.indexOf(o);i.forEach((u,h)=>{u[c]=e.dataY[h][l]})}),n=t,a=i):r===Lk.ReplaceAll&&(n=e.dataX,a=e.dataY):(n=[...t,...e.dataX],i.forEach((o,l)=>{let c=[...o,...e.dataY[l]];a.push(c)})),delete e.dataX,delete e.dataY,Object.assign(e,{xAxisData:n,data:a})}function kgt(s,e){var u,h;e.onBeforeValue||(e.onBeforeValue=Ugt);let t=e.calculative.canvas.store.data.scale;const i=e.calculative.worldRect.x,r=e.calculative.worldRect.y,n=e.calculative.worldRect.width,a=e.calculative.worldRect.height,o=!!e.echarts;e.echarts?(e.echarts.option.color||(e.echarts.option.color=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]),e.chartsColor=e.echarts.option.color):e.chartsColor||(e.chartsColor=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]);const l=o?e.echarts.option.series:e.data;let c=0;for(let d=0;dC+T.value,0):_=f.reduce((C,T)=>C+T.value,0);const y=p*parseFloat(o?f.radius[0]:e.chartsRadius[d][0])/100,v=p*parseFloat(o?f.radius[1]:e.chartsRadius[d][1])/100;if(y>v)return;let x=0,A=0;s.strokeStyle=o&&((u=f.itemStyle)==null?void 0:u.borderColor)||"#fff",s.lineWidth=(o&&((h=f.itemStyle)==null?void 0:h.borderWidth)||2)*t;const b=o?f.data:f;b.forEach((C,T)=>{var k,V,H,j,z,K,U,W,Z,q;A+=Math.PI*2*C.value/_,s.beginPath();let w=c+T;w>=e.chartsColor.length&&(w=w%e.chartsColor.length),s.fillStyle=o?e.echarts.option.color[w]:e.chartsColor[w],s.moveTo(m+y*Math.sin(A),g-y*Math.cos(A)),s.arc(m,g,y,-Math.PI/2+A,-Math.PI/2+x,!0),s.lineTo(m+v*Math.sin(x),g-v*Math.cos(x)),s.arc(m,g,v,-Math.PI/2+x,-Math.PI/2+A),s.lineTo(m+y*Math.sin(A),g-y*Math.cos(A)),s.stroke(),s.fill(),s.closePath();let P=(x+A)/2,M=m+(v+10*t)*Math.sin(P),R=g-(v+10*t)*Math.cos(P),I=s.fillStyle;f.label||(f.label={position:"outside",show:!0}),o&&["inner","inside"].includes(f.label.position)?(s.fillStyle="#ffffff",M=m+(v-y)/2*Math.sin(P),R=g-(v-y)/2*Math.cos(P)):o&&f.label.position=="outside",f.labelLine||(f.labelLine={show:!0}),(o&&f.labelLine.show!==!1||!o)&&(s.beginPath(),s.strokeStyle=o?e.echarts.option.color[c+T]:e.chartsColor[c+T],s.moveTo(m+v*Math.sin(P),g-v*Math.cos(P)),s.lineTo(M,R));let L={fontStyle:((k=e.tickLabel)==null?void 0:k.fontStyle)||e.calculative.fontStyle,fontWeight:((V=e.tickLabel)==null?void 0:V.fontWeight)||e.calculative.fontWeight,fontFamily:((H=e.tickLabel)==null?void 0:H.fontFamily)||e.calculative.fontFamily,lineHeight:((j=e.tickLabel)==null?void 0:j.lineHeight)||e.calculative.lineHeight,fontSize:(((z=e.tickLabel)==null?void 0:z.fontSize)||e.calculative.fontSize)*t};s.font=rp(L),s.textBaseline="middle",s.textAlign="center",P>Math.PI?((o&&f.label.position==="outside"||!o)&&(s.textAlign="end"),(o&&f.labelLine.show!==!1||!o&&(((U=(K=e.tickLabel)==null?void 0:K.labelLine)==null?void 0:U.show)??!0))&&s.lineTo(M-5*t,R),(o&&f.label.show!==!1||!o&&(((W=e.tickLabel)==null?void 0:W.show)??!0))&&s.fillText(C.name,M-5*t,R)):((o&&f.label.position==="outside"||!o)&&(s.textAlign="start"),(o&&f.labelLine.show!==!1||!o)&&s.lineTo(M+5*t,R),(o&&f.label.show!==!1||!o&&(((Z=e.tickLabel)==null?void 0:Z.show)??!0))&&s.fillText(C.name,M+5*t,R)),s.stroke(),s.closePath(),s.fillStyle=I,s.strokeStyle=o&&((q=f.itemStyle)==null?void 0:q.borderColor)||"#fff",x=A}),c+=b.length}}function Ugt(s,e){if(e.data||!e.dataX&&!e.dataY)return e;const t=s.data,i=s.replaceMode;let r=[];return i?i===Lk.Replace?(e.dataY.forEach((n,a)=>{n.forEach((o,l)=>{let c=t[a].filter(u=>u.name===o.name);c.length>0&&(c[0].value=o.value)})}),r=t):i===Lk.ReplaceAll&&(r=e.dataY):t.forEach((n,a)=>{let o=[...n,...e.dataY[a]];r.push(o)}),delete e.dataX,delete e.dataY,Object.assign(e,{data:r})}function zgt(s,e){e.onBeforeValue||(e.onBeforeValue=vFe);let t=e.calculative.canvas.store.data.scale;const i=e.calculative.worldRect.x,r=e.calculative.worldRect.y;e.calculative.worldRect.width;const n=e.calculative.worldRect.height;let a=[];if(e.echarts&&!e.echarts.option.color&&(e.echarts.option.color=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]),e.echarts)for(let h=0;hn?n/2*9/10:r/2*9/10,c=t+r/2,u=i+n/2,h=e.echarts?e.echarts.option.series[0].data[0].value:e.value,d,f=e.startAngle-e.endAngle,p=e.background||"#E6EBF8";s.strokeStyle=p;let m=l/10;s.lineWidth=m,s.beginPath(),s.lineCap="round",s.arc(c,u,l,-e.startAngle/180*Math.PI,-e.endAngle/180*Math.PI),s.stroke(),s.closePath();let g=0;if(e.axisLine&&!e.isClock)for(let te=e.axisLine.length-1;te>=0;te--)e.axisLine[te][0]*(e.max-e.min).02?s.textAlign="end":ne<-.02?s.textAlign="start":s.textAlign="center",pe>.02?s.textBaseline="top":pe<-.02?s.textBaseline="bottom":s.textBaseline="middle",s.fillText(Fgt(R*te+e.min),c+L*ne,u-L*pe),s.fill()}s.closePath();let k=1,V=["value"];if(e.isClock&&(k=3,V=["hourvalue","minutevalue","secondvalue"]),e.isClock)for(let te=0;te0&&(oe=(e.startAngle-(e[V[te]]-e.min)/(e.max*5-e.min)*f)/180*Math.PI);let ne=4/5*l;V[te]==="hourvalue"&&(ne=3/5*l),V[te]==="minutevalue"&&(ne=3.5/5*l);let pe=l*1/40;s.beginPath(),s.setLineDash([]),s.lineWidth=l/(te+1)/20,s.strokeStyle=e.color||"#999999",s.moveTo(c-pe*3*Math.cos(oe),u+pe*3*Math.sin(oe)),s.lineTo(c+ne*Math.cos(oe),u-ne*Math.sin(oe)),s.stroke()}else{let te=(e.startAngle-(h-e.min)/(e.max-e.min)*f)/180*Math.PI,oe=4/5*l,ne=l*1/40;s.beginPath(),s.setLineDash([]),s.lineWidth=2,s.fillStyle=d,s.moveTo(c-ne*3*Math.cos(te),u+ne*3*Math.sin(te)),s.lineTo(c+ne*Math.cos(te-Math.PI/2),u-ne*Math.sin(te-Math.PI/2)),s.lineTo(c+oe*Math.cos(te),u-oe*Math.sin(te)),s.lineTo(c+ne*Math.cos(te+Math.PI/2),u-ne*Math.sin(te+Math.PI/2)),s.lineTo(c-ne*3*Math.cos(te),u+ne*3*Math.sin(te)),s.fill()}s.beginPath(),s.textAlign="center",s.textBaseline="middle";let H={fontStyle:((ie=e.titleLabel)==null?void 0:ie.fontStyle)||e.calculative.fontStyle,textDecoration:((ae=e.titleLabel)==null?void 0:ae.textDecoration)||e.textDecoration,fontWeight:((ue=e.titleLabel)==null?void 0:ue.fontWeight)||e.calculative.fontWeight,fontFamily:((ce=e.titleLabel)==null?void 0:ce.fontFamily)||e.calculative.fontFamily,fontSize:(((N=e.titleLabel)==null?void 0:N.fontSize)||e.calculative.fontSize)*a,lineHeight:((B=e.titleLabel)==null?void 0:B.lineHeight)||e.calculative.lineHeight};s.font=rp(H),s.fillStyle=((Y=e.titleLabel)==null?void 0:Y.color)||d,e.isClock?s.fillText(("0"+parseInt(e.hourvalue)).slice(-2)+":"+("0"+parseInt(e.minutevalue)).slice(-2)+":"+("0"+parseInt(e.secondvalue)).slice(-2),c,u+l/2):s.fillText(h+" "+(e.unit||""),c,u+l/2),s.fill(),e.isClock&&(s.beginPath(),s.fillStyle=e.color||"#999999",s.strokeStyle="#ffffff",s.arc(c,u,l/20,0,Math.PI*2),s.stroke(),s.fill(),s.closePath())}function Ggt(s){if(s.isClock)s.clockInterval=setInterval(()=>{let e=new Date,t=e.getSeconds(),i=e.getMinutes()+t/60,r=e.getHours()%12+i/60;s.calculative.canvas.parent.setValue({id:s.id,hourvalue:r,minutevalue:i,secondvalue:t},{render:!0,doEvent:!1})},1e3);else{const e=s.value;s.value=0,s.frames=[{duration:2e3,value:e}],s.calculative.canvas.parent.startAnimate(s.id),setTimeout(()=>{s.value=e},1e3)}}function Wgt(s){s.clockInterval&&(clearInterval(s.clockInterval),s.clockInterval=void 0)}function Kgt(s){s.isClock&&(s.onDestroy(s),s.onAdd(s))}function Hgt(){return{lineChart:Bgt,histogram:zgt,pieChart:kgt,gauge:Vgt}}function jgt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/6,l=n/4;if(t.moveTo(i+l*2,r+0),t.lineTo(i+l*2,r+o),t.moveTo(i,r+o+l*2),t.arc(i+l*2,r+o+l*2,l*2,Math.PI*1,Math.PI*2,!1),t.lineTo(i+l*4,r+o*5),t.lineTo(i,r+o*5),t.lineTo(i,r+o+l*2),t.moveTo(i+l,r+o*5),t.lineTo(i+l,r+o*6),t.moveTo(i+l*2,r+o*5),t.lineTo(i+l*2,r+o*6),t.moveTo(i+l*3,r+o*5),t.lineTo(i+l*3,r+o*6),t.closePath(),t instanceof Path2D)return t}function MEe(s){const e=[{x:.5,y:0},{x:.25,y:1},{x:.5,y:1},{x:.75,y:1}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function Xgt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a-n,l=.5*n;if(t.moveTo(i+n/2,r),t.lineTo(i+n/2,r+o),t.moveTo(i+n,r+l+o),t.arc(i+n/2,r+l+o,l,0,Math.PI*2,!1),t.closePath(),t instanceof Path2D)return t}function REe(s){const e=[{x:.5,y:0},{x:.5,y:1}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function Ygt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/2,l=n/5;if(t.moveTo(i,r+o),t.lineTo(i+l,r+o),t.moveTo(i+l*5,r+o),t.ellipse(i+l*3,r+o,2*l,o,0,0,Math.PI*2),t.closePath(),t instanceof Path2D)return t}function Qgt(s){const e=[{x:.6,y:0},{x:1,y:.5},{x:.6,y:1},{x:0,y:.5}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function $gt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/4,l=.5*n;if(t.moveTo(i+l,r),t.lineTo(i+l,r+o),t.moveTo(i,r+o),t.rect(i,r+o,l*2,o*2),t.moveTo(i+l,r+3*o),t.lineTo(i+l,r+4*o),t.closePath(),t instanceof Path2D)return t}function Zgt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/8,l=.25*n;if(t.moveTo(i+l*2,r),t.lineTo(i+l*2,r+o*2),t.lineTo(i+l*3,r+o*3),t.lineTo(i+l*3,r+o*5),t.lineTo(i+l*2,r+o*6),t.lineTo(i+l*1,r+o*5),t.lineTo(i+l*1,r+o*3),t.lineTo(i+l*2,r+o*2),t.moveTo(i+l*3,r+o*4),t.lineTo(i+l*4,r+o*4),t.moveTo(i+l*2,r+o*6),t.lineTo(i+l*2,r+o*8),t.closePath(),t instanceof Path2D)return t}function qgt(s){const e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function Jgt(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=n/2,l=a/10;if(t.moveTo(i+o,r),t.lineTo(i+o,r+l),t.moveTo(i+o,r+l),t.quadraticCurveTo(i+o*2,r+l,i+o*2,r+l*9),t.moveTo(i+o,r+l),t.quadraticCurveTo(i,r+l,i,r+l*9),t.quadraticCurveTo(i+o,r+l*6,i+o*2,r+l*9),t.moveTo(i+o,r+a*3/4),t.lineTo(i+o,r+a),t.moveTo(i+o*2/5,r+a*201/250),t.lineTo(i+o*2/5,r+a),t.moveTo(i+o*8/5,r+a*201/250),t.lineTo(i+o*8/5,r+a),t.closePath(),t instanceof Path2D)return t}function IEe(s){const e=[{x:.5,y:0},{x:.2,y:1},{x:.5,y:1},{x:.8,y:1}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function e1t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/6,l=n/4;if(t.moveTo(i+l*2,r+0),t.lineTo(i+l*2,r+o),t.moveTo(i,r+o+l*2),t.arc(i+l*2,r+o+l*2,l*2,Math.PI*1,Math.PI*2,!1),t.lineTo(i+l*4,r+o*5),t.lineTo(i,r+o*5),t.lineTo(i,r+o+l*2),t.moveTo(i,r+o*5-o/3),t.lineTo(i+l*4,r+o*5-o/3),t.moveTo(i+l,r+o*5),t.lineTo(i+l,r+o*6),t.moveTo(i+l*2,r+o*5),t.lineTo(i+l*2,r+o*6),t.moveTo(i+l*3,r+o*5),t.lineTo(i+l*3,r+o*6),t.closePath(),t instanceof Path2D)return t}function t1t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/4,l=.5*n;if(t.moveTo(i+l,r),t.lineTo(i+l,r+o),t.lineTo(i+l*2,r+o*2),t.lineTo(i+l*2,r+o*4),t.lineTo(i,r+o*4),t.lineTo(i,r+o*2),t.lineTo(i+l,r+o),t.closePath(),t instanceof Path2D)return t}function i1t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/4,l=n/2;if(t.moveTo(i+l,r),t.lineTo(i+l,r+o),t.lineTo(i+l*2,r+o*4),t.lineTo(i,r+o*4),t.lineTo(i+l,r+o),t.closePath(),t instanceof Path2D)return t}function r1t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect,o=a/3,l=.5*n;if(t.moveTo(i+l,r),t.lineTo(i+l,r+o),t.lineTo(i+n,r+2*o),t.lineTo(i+l,r+a),t.lineTo(i,r+2*o),t.lineTo(i+l,r+o),t.closePath(),t instanceof Path2D)return t}function s1t(s){const e=[{x:.5,y:0},{x:1,y:.6666666666666666},{x:.5,y:1},{x:0,y:.6666666666666666}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function n1t(s,e){const t=e||new Path2D,{x:i,y:r,width:n,height:a}=s.calculative.worldRect;let o=n/2,l=a/10;if(t.moveTo(i+o,r),t.lineTo(i+o,r+l),t.moveTo(i+o,r+l),t.quadraticCurveTo(i+o*2,r+l,i+o*2,r+l*9),t.moveTo(i+o,r+l),t.quadraticCurveTo(i,r+l,i,r+l*9),t.quadraticCurveTo(i+o,r+l*6,i+o*2,r+l*9),t.moveTo(i,r+l*10),t.quadraticCurveTo(i+o,r+l*7,i+o*2,r+l*10),t.moveTo(i+o*2/5,r+a*201/250+l),t.lineTo(i+o*2/5,r+a),t.moveTo(i+o*8/5,r+a*201/250+l),t.lineTo(i+o*8/5,r+a),t.closePath(),t instanceof Path2D)return t}function a1t(s){const e=[{x:.5,y:0},{x:.2,y:1},{x:.8,y:1}];s.anchors=e.map(({x:t,y:i},r)=>({id:`${r}`,penId:s.id,x:t,y:i}))}function o1t(s,e){const{x:t,y:i,width:r,height:n}=e.calculative.worldRect,a=r/2,o=n/10;s.beginPath(),s.moveTo(t+a,i),s.lineTo(t+a,i+o),s.moveTo(t+a,i+o),s.quadraticCurveTo(t+a*2,i+o,t+a*2,i+o*9),s.moveTo(t+a,i+o),s.quadraticCurveTo(t,i+o,t,i+o*9),s.quadraticCurveTo(t+a,i+o*6,t+a*2,i+o*9),s.moveTo(t+a,i+n*3/4),s.lineTo(t+a,i+n*9/10),s.moveTo(t+a*2/5,i+n*201/250),s.lineTo(t+a*2/5,i+n*9/10),s.moveTo(t+a*8/5,i+n*201/250),s.lineTo(t+a*8/5,i+n*9/10),s.stroke(),s.closePath(),s.beginPath();const l=a*2>o*10?o:a/5;s.fillStyle="#333333",s.font=l+"px Arial",s.textBaseline="bottom",s.textAlign="center",s.fillText("o",t+a,i+n),s.fillText("m",t+a*2/5,i+n),s.fillText("o",t+a*8/5,i+n),s.closePath()}function l1t(){return{andGate:jgt,basicEvent:Xgt,conditionalEvent:Ygt,event:$gt,forbiddenGate:Zgt,orGate:Jgt,priorityAndGate:e1t,switchEvent:t1t,transferSymbol:i1t,unexpandedEvent:r1t,xorGate:n1t}}function c1t(){return{votingGate:o1t}}function u1t(){return{andGate:MEe,orGate:IEe,priorityAndGate:MEe,votingGate:IEe,xorGate:a1t,forbiddenGate:qgt,basicEvent:REe,unexpandedEvent:s1t,conditionalEvent:Qgt,transferSymbol:REe}}var yFe={exports:{}},zse={exports:{}};const h1t={},d1t=Object.freeze(Object.defineProperty({__proto__:null,default:h1t},Symbol.toStringTag,{value:"Module"})),xFe=rNe(d1t);var PEe;function pn(){return PEe||(PEe=1,function(s,e){(function(t,i){s.exports=i()})(Xt,function(){var t=t||function(i,r){var n;if(typeof window<"u"&&window.crypto&&(n=window.crypto),typeof self<"u"&&self.crypto&&(n=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(n=globalThis.crypto),!n&&typeof window<"u"&&window.msCrypto&&(n=window.msCrypto),!n&&typeof Xt<"u"&&Xt.crypto&&(n=Xt.crypto),!n&&typeof W1=="function")try{n=xFe}catch{}var a=function(){if(n){if(typeof n.getRandomValues=="function")try{return n.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof n.randomBytes=="function")try{return n.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function y(){}return function(v){var x;return y.prototype=v,x=new y,y.prototype=null,x}}(),l={},c=l.lib={},u=c.Base=function(){return{extend:function(y){var v=o(this);return y&&v.mixIn(y),(!v.hasOwnProperty("init")||this.init===v.init)&&(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var y=this.extend();return y.init.apply(y,arguments),y},init:function(){},mixIn:function(y){for(var v in y)y.hasOwnProperty(v)&&(this[v]=y[v]);y.hasOwnProperty("toString")&&(this.toString=y.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),h=c.WordArray=u.extend({init:function(y,v){y=this.words=y||[],v!=r?this.sigBytes=v:this.sigBytes=y.length*4},toString:function(y){return(y||f).stringify(this)},concat:function(y){var v=this.words,x=y.words,A=this.sigBytes,b=y.sigBytes;if(this.clamp(),A%4)for(var C=0;C>>2]>>>24-C%4*8&255;v[A+C>>>2]|=T<<24-(A+C)%4*8}else for(var w=0;w>>2]=x[w>>>2];return this.sigBytes+=b,this},clamp:function(){var y=this.words,v=this.sigBytes;y[v>>>2]&=4294967295<<32-v%4*8,y.length=i.ceil(v/4)},clone:function(){var y=u.clone.call(this);return y.words=this.words.slice(0),y},random:function(y){for(var v=[],x=0;x>>2]>>>24-b%4*8&255;A.push((C>>>4).toString(16)),A.push((C&15).toString(16))}return A.join("")},parse:function(y){for(var v=y.length,x=[],A=0;A>>3]|=parseInt(y.substr(A,2),16)<<24-A%8*4;return new h.init(x,v/2)}},p=d.Latin1={stringify:function(y){for(var v=y.words,x=y.sigBytes,A=[],b=0;b>>2]>>>24-b%4*8&255;A.push(String.fromCharCode(C))}return A.join("")},parse:function(y){for(var v=y.length,x=[],A=0;A>>2]|=(y.charCodeAt(A)&255)<<24-A%4*8;return new h.init(x,v)}},m=d.Utf8={stringify:function(y){try{return decodeURIComponent(escape(p.stringify(y)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(y){return p.parse(unescape(encodeURIComponent(y)))}},g=c.BufferedBlockAlgorithm=u.extend({reset:function(){this._data=new h.init,this._nDataBytes=0},_append:function(y){typeof y=="string"&&(y=m.parse(y)),this._data.concat(y),this._nDataBytes+=y.sigBytes},_process:function(y){var v,x=this._data,A=x.words,b=x.sigBytes,C=this.blockSize,T=C*4,w=b/T;y?w=i.ceil(w):w=i.max((w|0)-this._minBufferSize,0);var P=w*C,M=i.min(P*4,b);if(P){for(var R=0;R>>2]|=l[h]<<24-h%4*8;a.call(this,u,c)}else a.apply(this,arguments)};o.prototype=n}}(),t.lib.WordArray})}(Gse)),Gse.exports}var Wse={exports:{}},LEe;function p1t(){return LEe||(LEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.WordArray,a=i.enc;a.Utf16=a.Utf16BE={stringify:function(l){for(var c=l.words,u=l.sigBytes,h=[],d=0;d>>2]>>>16-d%4*8&65535;h.push(String.fromCharCode(f))}return h.join("")},parse:function(l){for(var c=l.length,u=[],h=0;h>>1]|=l.charCodeAt(h)<<16-h%2*16;return n.create(u,c*2)}},a.Utf16LE={stringify:function(l){for(var c=l.words,u=l.sigBytes,h=[],d=0;d>>2]>>>16-d%4*8&65535);h.push(String.fromCharCode(f))}return h.join("")},parse:function(l){for(var c=l.length,u=[],h=0;h>>1]|=o(l.charCodeAt(h)<<16-h%2*16);return n.create(u,c*2)}};function o(l){return l<<8&4278255360|l>>>8&16711935}}(),t.enc.Utf16})}(Wse)),Wse.exports}var Kse={exports:{}},OEe;function JE(){return OEe||(OEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.WordArray,a=i.enc;a.Base64={stringify:function(l){var c=l.words,u=l.sigBytes,h=this._map;l.clamp();for(var d=[],f=0;f>>2]>>>24-f%4*8&255,m=c[f+1>>>2]>>>24-(f+1)%4*8&255,g=c[f+2>>>2]>>>24-(f+2)%4*8&255,_=p<<16|m<<8|g,y=0;y<4&&f+y*.75>>6*(3-y)&63));var v=h.charAt(64);if(v)for(;d.length%4;)d.push(v);return d.join("")},parse:function(l){var c=l.length,u=this._map,h=this._reverseMap;if(!h){h=this._reverseMap=[];for(var d=0;d>>6-f%4*2,g=p|m;h[d>>>2]|=g<<24-d%4*8,d++}return n.create(h,d)}}(),t.enc.Base64})}(Kse)),Kse.exports}var Hse={exports:{}},NEe;function m1t(){return NEe||(NEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.WordArray,a=i.enc;a.Base64url={stringify:function(l,c){c===void 0&&(c=!0);var u=l.words,h=l.sigBytes,d=c?this._safe_map:this._map;l.clamp();for(var f=[],p=0;p>>2]>>>24-p%4*8&255,g=u[p+1>>>2]>>>24-(p+1)%4*8&255,_=u[p+2>>>2]>>>24-(p+2)%4*8&255,y=m<<16|g<<8|_,v=0;v<4&&p+v*.75>>6*(3-v)&63));var x=d.charAt(64);if(x)for(;f.length%4;)f.push(x);return f.join("")},parse:function(l,c){c===void 0&&(c=!0);var u=l.length,h=c?this._safe_map:this._map,d=this._reverseMap;if(!d){d=this._reverseMap=[];for(var f=0;f>>6-f%4*2,g=p|m;h[d>>>2]|=g<<24-d%4*8,d++}return n.create(h,d)}}(),t.enc.Base64url})}(Hse)),Hse.exports}var jse={exports:{}},FEe;function eT(){return FEe||(FEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){return function(i){var r=t,n=r.lib,a=n.WordArray,o=n.Hasher,l=r.algo,c=[];(function(){for(var m=0;m<64;m++)c[m]=i.abs(i.sin(m+1))*4294967296|0})();var u=l.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(m,g){for(var _=0;_<16;_++){var y=g+_,v=m[y];m[y]=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360}var x=this._hash.words,A=m[g+0],b=m[g+1],C=m[g+2],T=m[g+3],w=m[g+4],P=m[g+5],M=m[g+6],R=m[g+7],I=m[g+8],L=m[g+9],k=m[g+10],V=m[g+11],H=m[g+12],j=m[g+13],z=m[g+14],K=m[g+15],U=x[0],W=x[1],Z=x[2],q=x[3];U=h(U,W,Z,q,A,7,c[0]),q=h(q,U,W,Z,b,12,c[1]),Z=h(Z,q,U,W,C,17,c[2]),W=h(W,Z,q,U,T,22,c[3]),U=h(U,W,Z,q,w,7,c[4]),q=h(q,U,W,Z,P,12,c[5]),Z=h(Z,q,U,W,M,17,c[6]),W=h(W,Z,q,U,R,22,c[7]),U=h(U,W,Z,q,I,7,c[8]),q=h(q,U,W,Z,L,12,c[9]),Z=h(Z,q,U,W,k,17,c[10]),W=h(W,Z,q,U,V,22,c[11]),U=h(U,W,Z,q,H,7,c[12]),q=h(q,U,W,Z,j,12,c[13]),Z=h(Z,q,U,W,z,17,c[14]),W=h(W,Z,q,U,K,22,c[15]),U=d(U,W,Z,q,b,5,c[16]),q=d(q,U,W,Z,M,9,c[17]),Z=d(Z,q,U,W,V,14,c[18]),W=d(W,Z,q,U,A,20,c[19]),U=d(U,W,Z,q,P,5,c[20]),q=d(q,U,W,Z,k,9,c[21]),Z=d(Z,q,U,W,K,14,c[22]),W=d(W,Z,q,U,w,20,c[23]),U=d(U,W,Z,q,L,5,c[24]),q=d(q,U,W,Z,z,9,c[25]),Z=d(Z,q,U,W,T,14,c[26]),W=d(W,Z,q,U,I,20,c[27]),U=d(U,W,Z,q,j,5,c[28]),q=d(q,U,W,Z,C,9,c[29]),Z=d(Z,q,U,W,R,14,c[30]),W=d(W,Z,q,U,H,20,c[31]),U=f(U,W,Z,q,P,4,c[32]),q=f(q,U,W,Z,I,11,c[33]),Z=f(Z,q,U,W,V,16,c[34]),W=f(W,Z,q,U,z,23,c[35]),U=f(U,W,Z,q,b,4,c[36]),q=f(q,U,W,Z,w,11,c[37]),Z=f(Z,q,U,W,R,16,c[38]),W=f(W,Z,q,U,k,23,c[39]),U=f(U,W,Z,q,j,4,c[40]),q=f(q,U,W,Z,A,11,c[41]),Z=f(Z,q,U,W,T,16,c[42]),W=f(W,Z,q,U,M,23,c[43]),U=f(U,W,Z,q,L,4,c[44]),q=f(q,U,W,Z,H,11,c[45]),Z=f(Z,q,U,W,K,16,c[46]),W=f(W,Z,q,U,C,23,c[47]),U=p(U,W,Z,q,A,6,c[48]),q=p(q,U,W,Z,R,10,c[49]),Z=p(Z,q,U,W,z,15,c[50]),W=p(W,Z,q,U,P,21,c[51]),U=p(U,W,Z,q,H,6,c[52]),q=p(q,U,W,Z,T,10,c[53]),Z=p(Z,q,U,W,k,15,c[54]),W=p(W,Z,q,U,b,21,c[55]),U=p(U,W,Z,q,I,6,c[56]),q=p(q,U,W,Z,K,10,c[57]),Z=p(Z,q,U,W,M,15,c[58]),W=p(W,Z,q,U,j,21,c[59]),U=p(U,W,Z,q,w,6,c[60]),q=p(q,U,W,Z,V,10,c[61]),Z=p(Z,q,U,W,C,15,c[62]),W=p(W,Z,q,U,L,21,c[63]),x[0]=x[0]+U|0,x[1]=x[1]+W|0,x[2]=x[2]+Z|0,x[3]=x[3]+q|0},_doFinalize:function(){var m=this._data,g=m.words,_=this._nDataBytes*8,y=m.sigBytes*8;g[y>>>5]|=128<<24-y%32;var v=i.floor(_/4294967296),x=_;g[(y+64>>>9<<4)+15]=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,g[(y+64>>>9<<4)+14]=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,m.sigBytes=(g.length+1)*4,this._process();for(var A=this._hash,b=A.words,C=0;C<4;C++){var T=b[C];b[C]=(T<<8|T>>>24)&16711935|(T<<24|T>>>8)&4278255360}return A},clone:function(){var m=o.clone.call(this);return m._hash=this._hash.clone(),m}});function h(m,g,_,y,v,x,A){var b=m+(g&_|~g&y)+v+A;return(b<>>32-x)+g}function d(m,g,_,y,v,x,A){var b=m+(g&y|_&~y)+v+A;return(b<>>32-x)+g}function f(m,g,_,y,v,x,A){var b=m+(g^_^y)+v+A;return(b<>>32-x)+g}function p(m,g,_,y,v,x,A){var b=m+(_^(g|~y))+v+A;return(b<>>32-x)+g}r.MD5=o._createHelper(u),r.HmacMD5=o._createHmacHelper(u)}(Math),t.MD5})}(jse)),jse.exports}var Xse={exports:{}},BEe;function AFe(){return BEe||(BEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.WordArray,a=r.Hasher,o=i.algo,l=[],c=o.SHA1=a.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(u,h){for(var d=this._hash.words,f=d[0],p=d[1],m=d[2],g=d[3],_=d[4],y=0;y<80;y++){if(y<16)l[y]=u[h+y]|0;else{var v=l[y-3]^l[y-8]^l[y-14]^l[y-16];l[y]=v<<1|v>>>31}var x=(f<<5|f>>>27)+_+l[y];y<20?x+=(p&m|~p&g)+1518500249:y<40?x+=(p^m^g)+1859775393:y<60?x+=(p&m|p&g|m&g)-1894007588:x+=(p^m^g)-899497514,_=g,g=m,m=p<<30|p>>>2,p=f,f=x}d[0]=d[0]+f|0,d[1]=d[1]+p|0,d[2]=d[2]+m|0,d[3]=d[3]+g|0,d[4]=d[4]+_|0},_doFinalize:function(){var u=this._data,h=u.words,d=this._nDataBytes*8,f=u.sigBytes*8;return h[f>>>5]|=128<<24-f%32,h[(f+64>>>9<<4)+14]=Math.floor(d/4294967296),h[(f+64>>>9<<4)+15]=d,u.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var u=a.clone.call(this);return u._hash=this._hash.clone(),u}});i.SHA1=a._createHelper(c),i.HmacSHA1=a._createHmacHelper(c)}(),t.SHA1})}(Xse)),Xse.exports}var Yse={exports:{}},kEe;function Xme(){return kEe||(kEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){return function(i){var r=t,n=r.lib,a=n.WordArray,o=n.Hasher,l=r.algo,c=[],u=[];(function(){function f(_){for(var y=i.sqrt(_),v=2;v<=y;v++)if(!(_%v))return!1;return!0}function p(_){return(_-(_|0))*4294967296|0}for(var m=2,g=0;g<64;)f(m)&&(g<8&&(c[g]=p(i.pow(m,1/2))),u[g]=p(i.pow(m,1/3)),g++),m++})();var h=[],d=l.SHA256=o.extend({_doReset:function(){this._hash=new a.init(c.slice(0))},_doProcessBlock:function(f,p){for(var m=this._hash.words,g=m[0],_=m[1],y=m[2],v=m[3],x=m[4],A=m[5],b=m[6],C=m[7],T=0;T<64;T++){if(T<16)h[T]=f[p+T]|0;else{var w=h[T-15],P=(w<<25|w>>>7)^(w<<14|w>>>18)^w>>>3,M=h[T-2],R=(M<<15|M>>>17)^(M<<13|M>>>19)^M>>>10;h[T]=P+h[T-7]+R+h[T-16]}var I=x&A^~x&b,L=g&_^g&y^_&y,k=(g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22),V=(x<<26|x>>>6)^(x<<21|x>>>11)^(x<<7|x>>>25),H=C+V+I+u[T]+h[T],j=k+L;C=b,b=A,A=x,x=v+H|0,v=y,y=_,_=g,g=H+j|0}m[0]=m[0]+g|0,m[1]=m[1]+_|0,m[2]=m[2]+y|0,m[3]=m[3]+v|0,m[4]=m[4]+x|0,m[5]=m[5]+A|0,m[6]=m[6]+b|0,m[7]=m[7]+C|0},_doFinalize:function(){var f=this._data,p=f.words,m=this._nDataBytes*8,g=f.sigBytes*8;return p[g>>>5]|=128<<24-g%32,p[(g+64>>>9<<4)+14]=i.floor(m/4294967296),p[(g+64>>>9<<4)+15]=m,f.sigBytes=p.length*4,this._process(),this._hash},clone:function(){var f=o.clone.call(this);return f._hash=this._hash.clone(),f}});r.SHA256=o._createHelper(d),r.HmacSHA256=o._createHmacHelper(d)}(Math),t.SHA256})}(Yse)),Yse.exports}var Qse={exports:{}},UEe;function g1t(){return UEe||(UEe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),Xme())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.WordArray,a=i.algo,o=a.SHA256,l=a.SHA224=o.extend({_doReset:function(){this._hash=new n.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var c=o._doFinalize.call(this);return c.sigBytes-=4,c}});i.SHA224=o._createHelper(l),i.HmacSHA224=o._createHmacHelper(l)}(),t.SHA224})}(Qse)),Qse.exports}var $se={exports:{}},zEe;function bFe(){return zEe||(zEe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),yJ())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.Hasher,a=i.x64,o=a.Word,l=a.WordArray,c=i.algo;function u(){return o.create.apply(o,arguments)}var h=[u(1116352408,3609767458),u(1899447441,602891725),u(3049323471,3964484399),u(3921009573,2173295548),u(961987163,4081628472),u(1508970993,3053834265),u(2453635748,2937671579),u(2870763221,3664609560),u(3624381080,2734883394),u(310598401,1164996542),u(607225278,1323610764),u(1426881987,3590304994),u(1925078388,4068182383),u(2162078206,991336113),u(2614888103,633803317),u(3248222580,3479774868),u(3835390401,2666613458),u(4022224774,944711139),u(264347078,2341262773),u(604807628,2007800933),u(770255983,1495990901),u(1249150122,1856431235),u(1555081692,3175218132),u(1996064986,2198950837),u(2554220882,3999719339),u(2821834349,766784016),u(2952996808,2566594879),u(3210313671,3203337956),u(3336571891,1034457026),u(3584528711,2466948901),u(113926993,3758326383),u(338241895,168717936),u(666307205,1188179964),u(773529912,1546045734),u(1294757372,1522805485),u(1396182291,2643833823),u(1695183700,2343527390),u(1986661051,1014477480),u(2177026350,1206759142),u(2456956037,344077627),u(2730485921,1290863460),u(2820302411,3158454273),u(3259730800,3505952657),u(3345764771,106217008),u(3516065817,3606008344),u(3600352804,1432725776),u(4094571909,1467031594),u(275423344,851169720),u(430227734,3100823752),u(506948616,1363258195),u(659060556,3750685593),u(883997877,3785050280),u(958139571,3318307427),u(1322822218,3812723403),u(1537002063,2003034995),u(1747873779,3602036899),u(1955562222,1575990012),u(2024104815,1125592928),u(2227730452,2716904306),u(2361852424,442776044),u(2428436474,593698344),u(2756734187,3733110249),u(3204031479,2999351573),u(3329325298,3815920427),u(3391569614,3928383900),u(3515267271,566280711),u(3940187606,3454069534),u(4118630271,4000239992),u(116418474,1914138554),u(174292421,2731055270),u(289380356,3203993006),u(460393269,320620315),u(685471733,587496836),u(852142971,1086792851),u(1017036298,365543100),u(1126000580,2618297676),u(1288033470,3409855158),u(1501505948,4234509866),u(1607167915,987167468),u(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=u()})();var f=c.SHA512=n.extend({_doReset:function(){this._hash=new l.init([new o.init(1779033703,4089235720),new o.init(3144134277,2227873595),new o.init(1013904242,4271175723),new o.init(2773480762,1595750129),new o.init(1359893119,2917565137),new o.init(2600822924,725511199),new o.init(528734635,4215389547),new o.init(1541459225,327033209)])},_doProcessBlock:function(p,m){for(var g=this._hash.words,_=g[0],y=g[1],v=g[2],x=g[3],A=g[4],b=g[5],C=g[6],T=g[7],w=_.high,P=_.low,M=y.high,R=y.low,I=v.high,L=v.low,k=x.high,V=x.low,H=A.high,j=A.low,z=b.high,K=b.low,U=C.high,W=C.low,Z=T.high,q=T.low,ie=w,ae=P,ue=M,ce=R,N=I,B=L,Y=k,te=V,oe=H,ne=j,pe=z,ye=K,Ie=U,Ne=W,Ve=Z,nt=q,Ke=0;Ke<80;Ke++){var Et,ft,Tt=d[Ke];if(Ke<16)ft=Tt.high=p[m+Ke*2]|0,Et=Tt.low=p[m+Ke*2+1]|0;else{var Zt=d[Ke-15],Ji=Zt.high,hi=Zt.low,hr=(Ji>>>1|hi<<31)^(Ji>>>8|hi<<24)^Ji>>>7,tr=(hi>>>1|Ji<<31)^(hi>>>8|Ji<<24)^(hi>>>7|Ji<<25),Jr=d[Ke-2],Ti=Jr.high,Yi=Jr.low,Si=(Ti>>>19|Yi<<13)^(Ti<<3|Yi>>>29)^Ti>>>6,dr=(Yi>>>19|Ti<<13)^(Yi<<3|Ti>>>29)^(Yi>>>6|Ti<<26),Hi=d[Ke-7],er=Hi.high,rr=Hi.low,Dr=d[Ke-16],Wt=Dr.high,ni=Dr.low;Et=tr+rr,ft=hr+er+(Et>>>0>>0?1:0),Et=Et+dr,ft=ft+Si+(Et>>>0>>0?1:0),Et=Et+ni,ft=ft+Wt+(Et>>>0>>0?1:0),Tt.high=ft,Tt.low=Et}var Yt=oe&pe^~oe&Ie,Ni=ne&ye^~ne&Ne,ar=ie&ue^ie&N^ue&N,Cr=ae&ce^ae&B^ce&B,xs=(ie>>>28|ae<<4)^(ie<<30|ae>>>2)^(ie<<25|ae>>>7),gn=(ae>>>28|ie<<4)^(ae<<30|ie>>>2)^(ae<<25|ie>>>7),As=(oe>>>14|ne<<18)^(oe>>>18|ne<<14)^(oe<<23|ne>>>9),jt=(ne>>>14|oe<<18)^(ne>>>18|oe<<14)^(ne<<23|oe>>>9),cs=h[Ke],Bn=cs.high,Cn=cs.low,or=nt+jt,wt=Ve+As+(or>>>0>>0?1:0),or=or+Ni,wt=wt+Yt+(or>>>0>>0?1:0),or=or+Cn,wt=wt+Bn+(or>>>0>>0?1:0),or=or+Et,wt=wt+ft+(or>>>0>>0?1:0),mi=gn+Cr,Vt=xs+ar+(mi>>>0>>0?1:0);Ve=Ie,nt=Ne,Ie=pe,Ne=ye,pe=oe,ye=ne,ne=te+or|0,oe=Y+wt+(ne>>>0>>0?1:0)|0,Y=N,te=B,N=ue,B=ce,ue=ie,ce=ae,ae=or+mi|0,ie=wt+Vt+(ae>>>0>>0?1:0)|0}P=_.low=P+ae,_.high=w+ie+(P>>>0>>0?1:0),R=y.low=R+ce,y.high=M+ue+(R>>>0>>0?1:0),L=v.low=L+B,v.high=I+N+(L>>>0>>0?1:0),V=x.low=V+te,x.high=k+Y+(V>>>0>>0?1:0),j=A.low=j+ne,A.high=H+oe+(j>>>0>>0?1:0),K=b.low=K+ye,b.high=z+pe+(K>>>0>>0?1:0),W=C.low=W+Ne,C.high=U+Ie+(W>>>0>>0?1:0),q=T.low=q+nt,T.high=Z+Ve+(q>>>0>>0?1:0)},_doFinalize:function(){var p=this._data,m=p.words,g=this._nDataBytes*8,_=p.sigBytes*8;m[_>>>5]|=128<<24-_%32,m[(_+128>>>10<<5)+30]=Math.floor(g/4294967296),m[(_+128>>>10<<5)+31]=g,p.sigBytes=m.length*4,this._process();var y=this._hash.toX32();return y},clone:function(){var p=n.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:1024/32});i.SHA512=n._createHelper(f),i.HmacSHA512=n._createHmacHelper(f)}(),t.SHA512})}($se)),$se.exports}var Zse={exports:{}},VEe;function _1t(){return VEe||(VEe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),yJ(),bFe())})(Xt,function(t){return function(){var i=t,r=i.x64,n=r.Word,a=r.WordArray,o=i.algo,l=o.SHA512,c=o.SHA384=l.extend({_doReset:function(){this._hash=new a.init([new n.init(3418070365,3238371032),new n.init(1654270250,914150663),new n.init(2438529370,812702999),new n.init(355462360,4144912697),new n.init(1731405415,4290775857),new n.init(2394180231,1750603025),new n.init(3675008525,1694076839),new n.init(1203062813,3204075428)])},_doFinalize:function(){var u=l._doFinalize.call(this);return u.sigBytes-=16,u}});i.SHA384=l._createHelper(c),i.HmacSHA384=l._createHmacHelper(c)}(),t.SHA384})}(Zse)),Zse.exports}var qse={exports:{}},GEe;function v1t(){return GEe||(GEe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),yJ())})(Xt,function(t){return function(i){var r=t,n=r.lib,a=n.WordArray,o=n.Hasher,l=r.x64,c=l.Word,u=r.algo,h=[],d=[],f=[];(function(){for(var g=1,_=0,y=0;y<24;y++){h[g+5*_]=(y+1)*(y+2)/2%64;var v=_%5,x=(2*g+3*_)%5;g=v,_=x}for(var g=0;g<5;g++)for(var _=0;_<5;_++)d[g+5*_]=_+(2*g+3*_)%5*5;for(var A=1,b=0;b<24;b++){for(var C=0,T=0,w=0;w<7;w++){if(A&1){var P=(1<>>24)&16711935|(A<<24|A>>>8)&4278255360,b=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;var C=y[x];C.high^=b,C.low^=A}for(var T=0;T<24;T++){for(var w=0;w<5;w++){for(var P=0,M=0,R=0;R<5;R++){var C=y[w+5*R];P^=C.high,M^=C.low}var I=p[w];I.high=P,I.low=M}for(var w=0;w<5;w++)for(var L=p[(w+4)%5],k=p[(w+1)%5],V=k.high,H=k.low,P=L.high^(V<<1|H>>>31),M=L.low^(H<<1|V>>>31),R=0;R<5;R++){var C=y[w+5*R];C.high^=P,C.low^=M}for(var j=1;j<25;j++){var P,M,C=y[j],z=C.high,K=C.low,U=h[j];U<32?(P=z<>>32-U,M=K<>>32-U):(P=K<>>64-U,M=z<>>64-U);var W=p[d[j]];W.high=P,W.low=M}var Z=p[0],q=y[0];Z.high=q.high,Z.low=q.low;for(var w=0;w<5;w++)for(var R=0;R<5;R++){var j=w+5*R,C=y[j],ie=p[j],ae=p[(w+1)%5+5*R],ue=p[(w+2)%5+5*R];C.high=ie.high^~ae.high&ue.high,C.low=ie.low^~ae.low&ue.low}var C=y[0],ce=f[T];C.high^=ce.high,C.low^=ce.low}},_doFinalize:function(){var g=this._data,_=g.words;this._nDataBytes*8;var y=g.sigBytes*8,v=this.blockSize*32;_[y>>>5]|=1<<24-y%32,_[(i.ceil((y+1)/v)*v>>>5)-1]|=128,g.sigBytes=_.length*4,this._process();for(var x=this._state,A=this.cfg.outputLength/8,b=A/8,C=[],T=0;T>>24)&16711935|(P<<24|P>>>8)&4278255360,M=(M<<8|M>>>24)&16711935|(M<<24|M>>>8)&4278255360,C.push(M),C.push(P)}return new a.init(C,A)},clone:function(){for(var g=o.clone.call(this),_=g._state=this._state.slice(0),y=0;y<25;y++)_[y]=_[y].clone();return g}});r.SHA3=o._createHelper(m),r.HmacSHA3=o._createHmacHelper(m)}(Math),t.SHA3})}(qse)),qse.exports}var Jse={exports:{}},WEe;function y1t(){return WEe||(WEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){/** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */return function(i){var r=t,n=r.lib,a=n.WordArray,o=n.Hasher,l=r.algo,c=a.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),u=a.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),h=a.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=a.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),f=a.create([0,1518500249,1859775393,2400959708,2840853838]),p=a.create([1352829926,1548603684,1836072691,2053994217,0]),m=l.RIPEMD160=o.extend({_doReset:function(){this._hash=a.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(b,C){for(var T=0;T<16;T++){var w=C+T,P=b[w];b[w]=(P<<8|P>>>24)&16711935|(P<<24|P>>>8)&4278255360}var M=this._hash.words,R=f.words,I=p.words,L=c.words,k=u.words,V=h.words,H=d.words,j,z,K,U,W,Z,q,ie,ae,ue;Z=j=M[0],q=z=M[1],ie=K=M[2],ae=U=M[3],ue=W=M[4];for(var ce,T=0;T<80;T+=1)ce=j+b[C+L[T]]|0,T<16?ce+=g(z,K,U)+R[0]:T<32?ce+=_(z,K,U)+R[1]:T<48?ce+=y(z,K,U)+R[2]:T<64?ce+=v(z,K,U)+R[3]:ce+=x(z,K,U)+R[4],ce=ce|0,ce=A(ce,V[T]),ce=ce+W|0,j=W,W=U,U=A(K,10),K=z,z=ce,ce=Z+b[C+k[T]]|0,T<16?ce+=x(q,ie,ae)+I[0]:T<32?ce+=v(q,ie,ae)+I[1]:T<48?ce+=y(q,ie,ae)+I[2]:T<64?ce+=_(q,ie,ae)+I[3]:ce+=g(q,ie,ae)+I[4],ce=ce|0,ce=A(ce,H[T]),ce=ce+ue|0,Z=ue,ue=ae,ae=A(ie,10),ie=q,q=ce;ce=M[1]+K+ae|0,M[1]=M[2]+U+ue|0,M[2]=M[3]+W+Z|0,M[3]=M[4]+j+q|0,M[4]=M[0]+z+ie|0,M[0]=ce},_doFinalize:function(){var b=this._data,C=b.words,T=this._nDataBytes*8,w=b.sigBytes*8;C[w>>>5]|=128<<24-w%32,C[(w+64>>>9<<4)+14]=(T<<8|T>>>24)&16711935|(T<<24|T>>>8)&4278255360,b.sigBytes=(C.length+1)*4,this._process();for(var P=this._hash,M=P.words,R=0;R<5;R++){var I=M[R];M[R]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}return P},clone:function(){var b=o.clone.call(this);return b._hash=this._hash.clone(),b}});function g(b,C,T){return b^C^T}function _(b,C,T){return b&C|~b&T}function y(b,C,T){return(b|~C)^T}function v(b,C,T){return b&T|C&~T}function x(b,C,T){return b^(C|~T)}function A(b,C){return b<>>32-C}r.RIPEMD160=o._createHelper(m),r.HmacRIPEMD160=o._createHmacHelper(m)}(),t.RIPEMD160})}(Jse)),Jse.exports}var ene={exports:{}},KEe;function Yme(){return KEe||(KEe=1,function(s,e){(function(t,i){s.exports=i(pn())})(Xt,function(t){(function(){var i=t,r=i.lib,n=r.Base,a=i.enc,o=a.Utf8,l=i.algo;l.HMAC=n.extend({init:function(c,u){c=this._hasher=new c.init,typeof u=="string"&&(u=o.parse(u));var h=c.blockSize,d=h*4;u.sigBytes>d&&(u=c.finalize(u)),u.clamp();for(var f=this._oKey=u.clone(),p=this._iKey=u.clone(),m=f.words,g=p.words,_=0;_>>2]&255;P.sigBytes-=M}};n.BlockCipher=f.extend({cfg:f.cfg.extend({mode:g,padding:y}),reset:function(){var P;f.reset.call(this);var M=this.cfg,R=M.iv,I=M.mode;this._xformMode==this._ENC_XFORM_MODE?P=I.createEncryptor:(P=I.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==P?this._mode.init(this,R&&R.words):(this._mode=P.call(I,this,R&&R.words),this._mode.__creator=P)},_doProcessBlock:function(P,M){this._mode.processBlock(P,M)},_doFinalize:function(){var P,M=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(M.pad(this._data,this.blockSize),P=this._process(!0)):(P=this._process(!0),M.unpad(P)),P},blockSize:128/32});var v=n.CipherParams=a.extend({init:function(P){this.mixIn(P)},toString:function(P){return(P||this.formatter).stringify(this)}}),x=r.format={},A=x.OpenSSL={stringify:function(P){var M,R=P.ciphertext,I=P.salt;return I?M=o.create([1398893684,1701076831]).concat(I).concat(R):M=R,M.toString(u)},parse:function(P){var M,R=u.parse(P),I=R.words;return I[0]==1398893684&&I[1]==1701076831&&(M=o.create(I.slice(2,4)),I.splice(0,4),R.sigBytes-=16),v.create({ciphertext:R,salt:M})}},b=n.SerializableCipher=a.extend({cfg:a.extend({format:A}),encrypt:function(P,M,R,I){I=this.cfg.extend(I);var L=P.createEncryptor(R,I),k=L.finalize(M),V=L.cfg;return v.create({ciphertext:k,key:R,iv:V.iv,algorithm:P,mode:V.mode,padding:V.padding,blockSize:P.blockSize,formatter:I.format})},decrypt:function(P,M,R,I){I=this.cfg.extend(I),M=this._parse(M,I.format);var L=P.createDecryptor(R,I).finalize(M.ciphertext);return L},_parse:function(P,M){return typeof P=="string"?M.parse(P,this):P}}),C=r.kdf={},T=C.OpenSSL={execute:function(P,M,R,I,L){if(I||(I=o.random(64/8)),L)var k=d.create({keySize:M+R,hasher:L}).compute(P,I);else var k=d.create({keySize:M+R}).compute(P,I);var V=o.create(k.words.slice(M),R*4);return k.sigBytes=M*4,v.create({key:k,iv:V,salt:I})}},w=n.PasswordBasedCipher=b.extend({cfg:b.cfg.extend({kdf:T}),encrypt:function(P,M,R,I){I=this.cfg.extend(I);var L=I.kdf.execute(R,P.keySize,P.ivSize,I.salt,I.hasher);I.iv=L.iv;var k=b.encrypt.call(this,P,M,L.key,I);return k.mixIn(L),k},decrypt:function(P,M,R,I){I=this.cfg.extend(I),M=this._parse(M,I.format);var L=I.kdf.execute(R,P.keySize,P.ivSize,M.salt,I.hasher);I.iv=L.iv;var k=b.decrypt.call(this,P,M,L.key,I);return k}})}()})}(rne)),rne.exports}var sne={exports:{}},YEe;function A1t(){return YEe||(YEe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),uu())})(Xt,function(t){return t.mode.CFB=function(){var i=t.lib.BlockCipherMode.extend();i.Encryptor=i.extend({processBlock:function(n,a){var o=this._cipher,l=o.blockSize;r.call(this,n,a,l,o),this._prevBlock=n.slice(a,a+l)}}),i.Decryptor=i.extend({processBlock:function(n,a){var o=this._cipher,l=o.blockSize,c=n.slice(a,a+l);r.call(this,n,a,l,o),this._prevBlock=c}});function r(n,a,o,l){var c,u=this._iv;u?(c=u.slice(0),this._iv=void 0):c=this._prevBlock,l.encryptBlock(c,0);for(var h=0;h>24&255)===255){var l=o>>16&255,c=o>>8&255,u=o&255;l===255?(l=0,c===255?(c=0,u===255?u=0:++u):++c):++l,o=0,o+=l<<16,o+=c<<8,o+=u}else o+=1<<24;return o}function n(o){return(o[0]=r(o[0]))===0&&(o[1]=r(o[1])),o}var a=i.Encryptor=i.extend({processBlock:function(o,l){var c=this._cipher,u=c.blockSize,h=this._iv,d=this._counter;h&&(d=this._counter=h.slice(0),this._iv=void 0),n(d);var f=d.slice(0);c.encryptBlock(f,0);for(var p=0;p>>2]|=o<<24-l%4*8,i.sigBytes+=o},unpad:function(i){var r=i.words[i.sigBytes-1>>>2]&255;i.sigBytes-=r}},t.pad.Ansix923})}(cne)),cne.exports}var une={exports:{}},eTe;function M1t(){return eTe||(eTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),uu())})(Xt,function(t){return t.pad.Iso10126={pad:function(i,r){var n=r*4,a=n-i.sigBytes%n;i.concat(t.lib.WordArray.random(a-1)).concat(t.lib.WordArray.create([a<<24],1))},unpad:function(i){var r=i.words[i.sigBytes-1>>>2]&255;i.sigBytes-=r}},t.pad.Iso10126})}(une)),une.exports}var hne={exports:{}},tTe;function R1t(){return tTe||(tTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),uu())})(Xt,function(t){return t.pad.Iso97971={pad:function(i,r){i.concat(t.lib.WordArray.create([2147483648],1)),t.pad.ZeroPadding.pad(i,r)},unpad:function(i){t.pad.ZeroPadding.unpad(i),i.sigBytes--}},t.pad.Iso97971})}(hne)),hne.exports}var dne={exports:{}},iTe;function I1t(){return iTe||(iTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),uu())})(Xt,function(t){return t.pad.ZeroPadding={pad:function(i,r){var n=r*4;i.clamp(),i.sigBytes+=n-(i.sigBytes%n||n)},unpad:function(i){for(var r=i.words,n=i.sigBytes-1,n=i.sigBytes-1;n>=0;n--)if(r[n>>>2]>>>24-n%4*8&255){i.sigBytes=n+1;break}}},t.pad.ZeroPadding})}(dne)),dne.exports}var fne={exports:{}},rTe;function P1t(){return rTe||(rTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),uu())})(Xt,function(t){return t.pad.NoPadding={pad:function(){},unpad:function(){}},t.pad.NoPadding})}(fne)),fne.exports}var pne={exports:{}},sTe;function w1t(){return sTe||(sTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),uu())})(Xt,function(t){return function(i){var r=t,n=r.lib,a=n.CipherParams,o=r.enc,l=o.Hex,c=r.format;c.Hex={stringify:function(u){return u.ciphertext.toString(l)},parse:function(u){var h=l.parse(u);return a.create({ciphertext:h})}}}(),t.format.Hex})}(pne)),pne.exports}var mne={exports:{}},nTe;function D1t(){return nTe||(nTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),JE(),eT(),kx(),uu())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.BlockCipher,a=i.algo,o=[],l=[],c=[],u=[],h=[],d=[],f=[],p=[],m=[],g=[];(function(){for(var v=[],x=0;x<256;x++)x<128?v[x]=x<<1:v[x]=x<<1^283;for(var A=0,b=0,x=0;x<256;x++){var C=b^b<<1^b<<2^b<<3^b<<4;C=C>>>8^C&255^99,o[A]=C,l[C]=A;var T=v[A],w=v[T],P=v[w],M=v[C]*257^C*16843008;c[A]=M<<24|M>>>8,u[A]=M<<16|M>>>16,h[A]=M<<8|M>>>24,d[A]=M;var M=P*16843009^w*65537^T*257^A*16843008;f[C]=M<<24|M>>>8,p[C]=M<<16|M>>>16,m[C]=M<<8|M>>>24,g[C]=M,A?(A=T^v[v[v[P^T]]],b^=v[v[b]]):A=b=1}})();var _=[0,1,2,4,8,16,32,64,128,27,54],y=a.AES=n.extend({_doReset:function(){var v;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var x=this._keyPriorReset=this._key,A=x.words,b=x.sigBytes/4,C=this._nRounds=b+6,T=(C+1)*4,w=this._keySchedule=[],P=0;P6&&P%b==4&&(v=o[v>>>24]<<24|o[v>>>16&255]<<16|o[v>>>8&255]<<8|o[v&255]):(v=v<<8|v>>>24,v=o[v>>>24]<<24|o[v>>>16&255]<<16|o[v>>>8&255]<<8|o[v&255],v^=_[P/b|0]<<24),w[P]=w[P-b]^v);for(var M=this._invKeySchedule=[],R=0;R>>24]]^p[o[v>>>16&255]]^m[o[v>>>8&255]]^g[o[v&255]]}}},encryptBlock:function(v,x){this._doCryptBlock(v,x,this._keySchedule,c,u,h,d,o)},decryptBlock:function(v,x){var A=v[x+1];v[x+1]=v[x+3],v[x+3]=A,this._doCryptBlock(v,x,this._invKeySchedule,f,p,m,g,l);var A=v[x+1];v[x+1]=v[x+3],v[x+3]=A},_doCryptBlock:function(v,x,A,b,C,T,w,P){for(var M=this._nRounds,R=v[x]^A[0],I=v[x+1]^A[1],L=v[x+2]^A[2],k=v[x+3]^A[3],V=4,H=1;H>>24]^C[I>>>16&255]^T[L>>>8&255]^w[k&255]^A[V++],z=b[I>>>24]^C[L>>>16&255]^T[k>>>8&255]^w[R&255]^A[V++],K=b[L>>>24]^C[k>>>16&255]^T[R>>>8&255]^w[I&255]^A[V++],U=b[k>>>24]^C[R>>>16&255]^T[I>>>8&255]^w[L&255]^A[V++];R=j,I=z,L=K,k=U}var j=(P[R>>>24]<<24|P[I>>>16&255]<<16|P[L>>>8&255]<<8|P[k&255])^A[V++],z=(P[I>>>24]<<24|P[L>>>16&255]<<16|P[k>>>8&255]<<8|P[R&255])^A[V++],K=(P[L>>>24]<<24|P[k>>>16&255]<<16|P[R>>>8&255]<<8|P[I&255])^A[V++],U=(P[k>>>24]<<24|P[R>>>16&255]<<16|P[I>>>8&255]<<8|P[L&255])^A[V++];v[x]=j,v[x+1]=z,v[x+2]=K,v[x+3]=U},keySize:256/32});i.AES=n._createHelper(y)}(),t.AES})}(mne)),mne.exports}var gne={exports:{}},aTe;function L1t(){return aTe||(aTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),JE(),eT(),kx(),uu())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.WordArray,a=r.BlockCipher,o=i.algo,l=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],c=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],u=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],h=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],d=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],f=o.DES=a.extend({_doReset:function(){for(var _=this._key,y=_.words,v=[],x=0;x<56;x++){var A=l[x]-1;v[x]=y[A>>>5]>>>31-A%32&1}for(var b=this._subKeys=[],C=0;C<16;C++){for(var T=b[C]=[],w=u[C],x=0;x<24;x++)T[x/6|0]|=v[(c[x]-1+w)%28]<<31-x%6,T[4+(x/6|0)]|=v[28+(c[x+24]-1+w)%28]<<31-x%6;T[0]=T[0]<<1|T[0]>>>31;for(var x=1;x<7;x++)T[x]=T[x]>>>(x-1)*4+3;T[7]=T[7]<<5|T[7]>>>27}for(var P=this._invSubKeys=[],x=0;x<16;x++)P[x]=b[15-x]},encryptBlock:function(_,y){this._doCryptBlock(_,y,this._subKeys)},decryptBlock:function(_,y){this._doCryptBlock(_,y,this._invSubKeys)},_doCryptBlock:function(_,y,v){this._lBlock=_[y],this._rBlock=_[y+1],p.call(this,4,252645135),p.call(this,16,65535),m.call(this,2,858993459),m.call(this,8,16711935),p.call(this,1,1431655765);for(var x=0;x<16;x++){for(var A=v[x],b=this._lBlock,C=this._rBlock,T=0,w=0;w<8;w++)T|=h[w][((C^A[w])&d[w])>>>0];this._lBlock=C,this._rBlock=b^T}var P=this._lBlock;this._lBlock=this._rBlock,this._rBlock=P,p.call(this,1,1431655765),m.call(this,8,16711935),m.call(this,2,858993459),p.call(this,16,65535),p.call(this,4,252645135),_[y]=this._lBlock,_[y+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function p(_,y){var v=(this._lBlock>>>_^this._rBlock)&y;this._rBlock^=v,this._lBlock^=v<<_}function m(_,y){var v=(this._rBlock>>>_^this._lBlock)&y;this._lBlock^=v,this._rBlock^=v<<_}i.DES=a._createHelper(f);var g=o.TripleDES=a.extend({_doReset:function(){var _=this._key,y=_.words;if(y.length!==2&&y.length!==4&&y.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var v=y.slice(0,2),x=y.length<4?y.slice(0,2):y.slice(2,4),A=y.length<6?y.slice(0,2):y.slice(4,6);this._des1=f.createEncryptor(n.create(v)),this._des2=f.createEncryptor(n.create(x)),this._des3=f.createEncryptor(n.create(A))},encryptBlock:function(_,y){this._des1.encryptBlock(_,y),this._des2.decryptBlock(_,y),this._des3.encryptBlock(_,y)},decryptBlock:function(_,y){this._des3.decryptBlock(_,y),this._des2.encryptBlock(_,y),this._des1.decryptBlock(_,y)},keySize:192/32,ivSize:64/32,blockSize:64/32});i.TripleDES=a._createHelper(g)}(),t.TripleDES})}(gne)),gne.exports}var _ne={exports:{}},oTe;function O1t(){return oTe||(oTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),JE(),eT(),kx(),uu())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.StreamCipher,a=i.algo,o=a.RC4=n.extend({_doReset:function(){for(var u=this._key,h=u.words,d=u.sigBytes,f=this._S=[],p=0;p<256;p++)f[p]=p;for(var p=0,m=0;p<256;p++){var g=p%d,_=h[g>>>2]>>>24-g%4*8&255;m=(m+f[p]+_)%256;var y=f[p];f[p]=f[m],f[m]=y}this._i=this._j=0},_doProcessBlock:function(u,h){u[h]^=l.call(this)},keySize:256/32,ivSize:0});function l(){for(var u=this._S,h=this._i,d=this._j,f=0,p=0;p<4;p++){h=(h+1)%256,d=(d+u[h])%256;var m=u[h];u[h]=u[d],u[d]=m,f|=u[(u[h]+u[d])%256]<<24-p*8}return this._i=h,this._j=d,f}i.RC4=n._createHelper(o);var c=a.RC4Drop=o.extend({cfg:o.cfg.extend({drop:192}),_doReset:function(){o._doReset.call(this);for(var u=this.cfg.drop;u>0;u--)l.call(this)}});i.RC4Drop=n._createHelper(c)}(),t.RC4})}(_ne)),_ne.exports}var vne={exports:{}},lTe;function N1t(){return lTe||(lTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),JE(),eT(),kx(),uu())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.StreamCipher,a=i.algo,o=[],l=[],c=[],u=a.Rabbit=n.extend({_doReset:function(){for(var d=this._key.words,f=this.cfg.iv,p=0;p<4;p++)d[p]=(d[p]<<8|d[p]>>>24)&16711935|(d[p]<<24|d[p]>>>8)&4278255360;var m=this._X=[d[0],d[3]<<16|d[2]>>>16,d[1],d[0]<<16|d[3]>>>16,d[2],d[1]<<16|d[0]>>>16,d[3],d[2]<<16|d[1]>>>16],g=this._C=[d[2]<<16|d[2]>>>16,d[0]&4294901760|d[1]&65535,d[3]<<16|d[3]>>>16,d[1]&4294901760|d[2]&65535,d[0]<<16|d[0]>>>16,d[2]&4294901760|d[3]&65535,d[1]<<16|d[1]>>>16,d[3]&4294901760|d[0]&65535];this._b=0;for(var p=0;p<4;p++)h.call(this);for(var p=0;p<8;p++)g[p]^=m[p+4&7];if(f){var _=f.words,y=_[0],v=_[1],x=(y<<8|y>>>24)&16711935|(y<<24|y>>>8)&4278255360,A=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,b=x>>>16|A&4294901760,C=A<<16|x&65535;g[0]^=x,g[1]^=b,g[2]^=A,g[3]^=C,g[4]^=x,g[5]^=b,g[6]^=A,g[7]^=C;for(var p=0;p<4;p++)h.call(this)}},_doProcessBlock:function(d,f){var p=this._X;h.call(this),o[0]=p[0]^p[5]>>>16^p[3]<<16,o[1]=p[2]^p[7]>>>16^p[5]<<16,o[2]=p[4]^p[1]>>>16^p[7]<<16,o[3]=p[6]^p[3]>>>16^p[1]<<16;for(var m=0;m<4;m++)o[m]=(o[m]<<8|o[m]>>>24)&16711935|(o[m]<<24|o[m]>>>8)&4278255360,d[f+m]^=o[m]},blockSize:128/32,ivSize:64/32});function h(){for(var d=this._X,f=this._C,p=0;p<8;p++)l[p]=f[p];f[0]=f[0]+1295307597+this._b|0,f[1]=f[1]+3545052371+(f[0]>>>0>>0?1:0)|0,f[2]=f[2]+886263092+(f[1]>>>0>>0?1:0)|0,f[3]=f[3]+1295307597+(f[2]>>>0>>0?1:0)|0,f[4]=f[4]+3545052371+(f[3]>>>0>>0?1:0)|0,f[5]=f[5]+886263092+(f[4]>>>0>>0?1:0)|0,f[6]=f[6]+1295307597+(f[5]>>>0>>0?1:0)|0,f[7]=f[7]+3545052371+(f[6]>>>0>>0?1:0)|0,this._b=f[7]>>>0>>0?1:0;for(var p=0;p<8;p++){var m=d[p]+f[p],g=m&65535,_=m>>>16,y=((g*g>>>17)+g*_>>>15)+_*_,v=((m&4294901760)*m|0)+((m&65535)*m|0);c[p]=y^v}d[0]=c[0]+(c[7]<<16|c[7]>>>16)+(c[6]<<16|c[6]>>>16)|0,d[1]=c[1]+(c[0]<<8|c[0]>>>24)+c[7]|0,d[2]=c[2]+(c[1]<<16|c[1]>>>16)+(c[0]<<16|c[0]>>>16)|0,d[3]=c[3]+(c[2]<<8|c[2]>>>24)+c[1]|0,d[4]=c[4]+(c[3]<<16|c[3]>>>16)+(c[2]<<16|c[2]>>>16)|0,d[5]=c[5]+(c[4]<<8|c[4]>>>24)+c[3]|0,d[6]=c[6]+(c[5]<<16|c[5]>>>16)+(c[4]<<16|c[4]>>>16)|0,d[7]=c[7]+(c[6]<<8|c[6]>>>24)+c[5]|0}i.Rabbit=n._createHelper(u)}(),t.Rabbit})}(vne)),vne.exports}var yne={exports:{}},cTe;function F1t(){return cTe||(cTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),JE(),eT(),kx(),uu())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.StreamCipher,a=i.algo,o=[],l=[],c=[],u=a.RabbitLegacy=n.extend({_doReset:function(){var d=this._key.words,f=this.cfg.iv,p=this._X=[d[0],d[3]<<16|d[2]>>>16,d[1],d[0]<<16|d[3]>>>16,d[2],d[1]<<16|d[0]>>>16,d[3],d[2]<<16|d[1]>>>16],m=this._C=[d[2]<<16|d[2]>>>16,d[0]&4294901760|d[1]&65535,d[3]<<16|d[3]>>>16,d[1]&4294901760|d[2]&65535,d[0]<<16|d[0]>>>16,d[2]&4294901760|d[3]&65535,d[1]<<16|d[1]>>>16,d[3]&4294901760|d[0]&65535];this._b=0;for(var g=0;g<4;g++)h.call(this);for(var g=0;g<8;g++)m[g]^=p[g+4&7];if(f){var _=f.words,y=_[0],v=_[1],x=(y<<8|y>>>24)&16711935|(y<<24|y>>>8)&4278255360,A=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,b=x>>>16|A&4294901760,C=A<<16|x&65535;m[0]^=x,m[1]^=b,m[2]^=A,m[3]^=C,m[4]^=x,m[5]^=b,m[6]^=A,m[7]^=C;for(var g=0;g<4;g++)h.call(this)}},_doProcessBlock:function(d,f){var p=this._X;h.call(this),o[0]=p[0]^p[5]>>>16^p[3]<<16,o[1]=p[2]^p[7]>>>16^p[5]<<16,o[2]=p[4]^p[1]>>>16^p[7]<<16,o[3]=p[6]^p[3]>>>16^p[1]<<16;for(var m=0;m<4;m++)o[m]=(o[m]<<8|o[m]>>>24)&16711935|(o[m]<<24|o[m]>>>8)&4278255360,d[f+m]^=o[m]},blockSize:128/32,ivSize:64/32});function h(){for(var d=this._X,f=this._C,p=0;p<8;p++)l[p]=f[p];f[0]=f[0]+1295307597+this._b|0,f[1]=f[1]+3545052371+(f[0]>>>0>>0?1:0)|0,f[2]=f[2]+886263092+(f[1]>>>0>>0?1:0)|0,f[3]=f[3]+1295307597+(f[2]>>>0>>0?1:0)|0,f[4]=f[4]+3545052371+(f[3]>>>0>>0?1:0)|0,f[5]=f[5]+886263092+(f[4]>>>0>>0?1:0)|0,f[6]=f[6]+1295307597+(f[5]>>>0>>0?1:0)|0,f[7]=f[7]+3545052371+(f[6]>>>0>>0?1:0)|0,this._b=f[7]>>>0>>0?1:0;for(var p=0;p<8;p++){var m=d[p]+f[p],g=m&65535,_=m>>>16,y=((g*g>>>17)+g*_>>>15)+_*_,v=((m&4294901760)*m|0)+((m&65535)*m|0);c[p]=y^v}d[0]=c[0]+(c[7]<<16|c[7]>>>16)+(c[6]<<16|c[6]>>>16)|0,d[1]=c[1]+(c[0]<<8|c[0]>>>24)+c[7]|0,d[2]=c[2]+(c[1]<<16|c[1]>>>16)+(c[0]<<16|c[0]>>>16)|0,d[3]=c[3]+(c[2]<<8|c[2]>>>24)+c[1]|0,d[4]=c[4]+(c[3]<<16|c[3]>>>16)+(c[2]<<16|c[2]>>>16)|0,d[5]=c[5]+(c[4]<<8|c[4]>>>24)+c[3]|0,d[6]=c[6]+(c[5]<<16|c[5]>>>16)+(c[4]<<16|c[4]>>>16)|0,d[7]=c[7]+(c[6]<<8|c[6]>>>24)+c[5]|0}i.RabbitLegacy=n._createHelper(u)}(),t.RabbitLegacy})}(yne)),yne.exports}var xne={exports:{}},uTe;function B1t(){return uTe||(uTe=1,function(s,e){(function(t,i,r){s.exports=i(pn(),JE(),eT(),kx(),uu())})(Xt,function(t){return function(){var i=t,r=i.lib,n=r.BlockCipher,a=i.algo;const o=16,l=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var u={pbox:[],sbox:[]};function h(g,_){let y=_>>24&255,v=_>>16&255,x=_>>8&255,A=_&255,b=g.sbox[0][y]+g.sbox[1][v];return b=b^g.sbox[2][x],b=b+g.sbox[3][A],b}function d(g,_,y){let v=_,x=y,A;for(let b=0;b1;--b)v=v^g.pbox[b],x=h(g,v)^x,A=v,v=x,x=A;return A=v,v=x,x=A,x=x^g.pbox[1],v=v^g.pbox[0],{left:v,right:x}}function p(g,_,y){for(let C=0;C<4;C++){g.sbox[C]=[];for(let T=0;T<256;T++)g.sbox[C][T]=c[C][T]}let v=0;for(let C=0;C=y&&(v=0);let x=0,A=0,b=0;for(let C=0;C{window.meta2d&&window.meta2d.render()}),document.head.appendChild(i)}var hTe=performance.now();function mC(s,e=!0){let t="/view/";t==="/"&&(t=""),location.host.indexOf(".le5le.")===-1&&(t=".",location.pathname.indexOf("/view")!==-1&&(t="/view"));const r=document.createElement("script");r.type="text/javascript",r.defer=e,r.src=t+s+"?r="+new Date().getTime(),r.addEventListener("load",()=>{const n=performance.now();(n>hTe+500||n>33)&&(e||(s.indexOf("echarts.min.js")!==-1&&z1t(),window.meta2d&&window.meta2d.scale(window.meta2d.store.data.scale)),window.meta2d&&window.meta2d.render(),hTe=n)}),document.body.appendChild(r)}function U1t(s){const e="blrtP0ilBMMMYtAt",t=DI.enc.Utf8.parse(e);return DI.AES.decrypt(s,DI.enc.Utf8.parse(e),{iv:t,mode:DI.mode.CBC,padding:DI.pad.Pkcs7}).toString(DI.enc.Utf8)}function h0(s,e){return e=e||window.location.search,new URLSearchParams(e).get(s)}function z1t(){let s="/view/";s==="/"&&(s=""),location.host.indexOf(".le5le.")===-1&&(s=".",location.pathname.indexOf("/view")!==-1&&(s="/view"));try{fetch(s+"/theme/dark.json").then(t=>t.json()).then(t=>{echarts.registerTheme("le-dark",t)}),fetch(s+"/theme/light.json").then(t=>t.json()).then(t=>{echarts.registerTheme("le-light",t)})}catch(t){console.warn(t)}}function ZP(s){var e,t=new RegExp("(^| )"+s+"=([^;]*)(;|$)");return(e=document.cookie.match(t))?decodeURIComponent(e[2]):""}function cue(s,e,t){var i=window,r=i.escape(s)+"="+i.escape(e)+";";if(t||(t={}),t.expires){var n=new Date(new Date().getTime()+t.expires*1e3*60*60*24);r+="expires="+n.toUTCString()+";"}t.path&&(r+="path="+t.path+";"),t.domain&&(r+="domain="+t.domain+";"),document.cookie=r}function tZ(s,e){ZP(s)&&(e||(e={}),e.expires=-1,cue(s,"",e))}var qP=function(){var s=location.hostname,e=s.split(".");return e.length<3||e.length===4&&+e[0]>0&&+e[1]>0&&+e[2]>0&&+e[3]>0?s="":s.endsWith(".com.cn")||s.endsWith(".org.cn")?s=e.slice(-3).join("."):s=e.slice(-2).join("."),s};function V1t(s){s.interceptors.request.use(function(e){return e.url.indexOf("/api/sso/profile")!==-1?e.headers.Authorization="Bearer "+W1t():e.headers.Authorization="Bearer "+Qme(),e.headers["Token-Extend-Type"]=ZP("remember")||"hours",e},function(e){return Promise.reject(e)})}function G1t(s){s.interceptors.response.use(function(e){var t;return!((t=e==null?void 0:e.headers)===null||t===void 0)&&t.token&&CFe(e.headers.token),e},function(e){e&&!e.response||e&&e.response&&(e.response.config.url.indexOf("/api/account/profile")!==-1&&H1t(),e.response.config.url.indexOf("/api/sso/profile")!==-1&&K1t())})}var b0;(function(s){s[s.None=0]="None",s[s.LocalStorage=1]="LocalStorage",s[s.Cookie=2]="Cookie"})(b0||(b0={}));var sz=location.host.indexOf("le5le.com")!==-1;function W1t(){var s,e=(s=globalThis.le5leSSOTokenName)!==null&&s!==void 0?s:"ssotoken";switch(globalThis.le5leSSOTokenType){case b0.LocalStorage:return localStorage.getItem(e);case b0.Cookie:return ZP(e);default:var t=sz?ZP(e):localStorage.getItem(e);return t}}function K1t(){var s,e=(s=globalThis.le5leSSOTokenName)!==null&&s!==void 0?s:"ssotoken";switch(globalThis.le5leSSOTokenType){case b0.LocalStorage:localStorage.removeItem(e);break;case b0.Cookie:tZ(e,{path:"/",domain:qP()});break;default:sz?tZ(e,{path:"/",domain:qP()}):localStorage.removeItem(e);break}}function Qme(){var s,e=(s=globalThis.le5leTokenName)!==null&&s!==void 0?s:"token";switch(globalThis.le5leTokenType){case b0.LocalStorage:return localStorage.getItem(e);case b0.Cookie:return ZP(e);default:var t=sz?ZP(e):localStorage.getItem(e);return t}}function CFe(s){var e,t=(e=globalThis.le5leTokenName)!==null&&e!==void 0?e:"token";switch(globalThis.le5leTokenType){case b0.LocalStorage:localStorage.setItem(t,s);break;case b0.Cookie:cue(t,s,{path:"/",domain:qP()});break;default:sz?cue(t,s,{path:"/",domain:qP()}):localStorage.setItem(t,s);break}}function H1t(){var s,e=(s=globalThis.le5leTokenName)!==null&&s!==void 0?s:"token";switch(globalThis.le5leTokenType){case b0.LocalStorage:localStorage.removeItem(e);break;case b0.Cookie:tZ(e,{path:"/",domain:qP()});break;default:sz?tZ(e,{path:"/",domain:qP()}):localStorage.removeItem(e);break}}const j1t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);function X1t(s){const e=h0("token")||Qme()||"";e&&s.pens.forEach(t=>{t.name=="iframe"&&t.iframe.includes("le5le.com")&&(t.iframe+="&token="+e)})}function SFe(s,e){const t=new oFe("app");Y1t(),Ane("/css/t/font_2395018_nng9x1qhat.css"),Ane("/css/t/font_2073009_teagntehxt.css"),Ane("/css/t/iconfont.css"),mC("/js/r.js");const i=["/js/marked.min.js","/js/echarts.min.js","/js/highcharts.js","/js/lcjs.iife.js"];for(let n=0;n{if(location.host.indexOf(".le5le.com")===-1)mC("/js/1.js"),setTimeout(async()=>{let a=".";location.pathname.indexOf("/view")!==-1&&(a="/view"),window.registerIot(window.enterpriseId||window.userId,`${a}/js/2d-components.js`),window.meta2dTools&®isterToolsNew&®isterToolsNew(),t.render()},1e3);else{for(let a=1;a<10;a++)mC("/js/"+a+".js");for(let a=97;a<110;a++)mC("/js/"+String.fromCharCode(a)+".js");mC("/js/2d-components.js")}},100),mC("/js/highcharts-more.js");const r=setInterval(()=>{!window.meta2dTools||window.meta2dTools.length<1450||registerToolsNew&&(registerToolsNew(),clearInterval(r))},200);s.locked=1,window.userId=s.userId,setTimeout(()=>{var l,c,u;X1t(s),t.open(s),t.setOptions({scroll:t.store.data.scroll,disableScale:t.store.data.isDisableScale,disableTranslate:t.store.data.isDisableTranslate}),t.canvas.opening=!1;const n=document.getElementById("lock");let a=null,o=null;if(n){a=n.querySelector(".locked"),o=n.querySelector(".unlock");let h=h0("locked");h&&h.endsWith("#")&&(h=h.slice(0,-1)),h==1?(t.setOptions({disableScale:!0,disableTranslate:!0}),a.style.display="block"):o.style.display="block";let d=h0("showLock");d&&d.endsWith("#")&&(d=d.slice(0,-1)),d==1&&(n.style.display="block",n.addEventListener("click",()=>{a.style.display==="block"?(t.setOptions({disableScale:!1,disableTranslate:!1}),a.style.display="none",o.style.display="block",Nf("已解锁,可以拖动和缩放画布",2e3,"success")):(t.setOptions({disableScale:!0,disableTranslate:!0}),a.style.display="block",o.style.display="none",Nf("已锁定,无法拖动和缩放画布",2e3,"warn"))}))}t.store.options.shadowColor="#0000",t.canvas.parentElement.style.background=t.store.data.background||((u=(c=t.store.theme)==null?void 0:c[(l=t.store.data)==null?void 0:l.theme])==null?void 0:u.background),t.fitView(!0,10)},1500),j1t&&setTimeout(()=>{t.fitView(!0,10)},5e3)}function Y1t(){R1(umt()),$ce(hmt()),R1(mmt()),_5(gmt()),R1(Cmt()),R1(Tmt()),_5(Mmt()),Qmt(),$mt(),Zmt(),_5(Dgt()),R1(Lgt()),_5(Hgt()),R1(l1t()),_5(c1t()),$ce(u1t())}const iZ={};function ve(s,e){iZ[s]=e}function Xn(s){return iZ[s]}function Q1t(s){for(const e in iZ)if(s instanceof iZ[e]&&!e.includes("Abstract"))return e;return"Unknown"}class Oa{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,r){for(const n in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,n)&&this._BabylonFileParsers[n](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}Oa._BabylonFileParsers={};Oa._IndividualBabylonFileParsers={};ve("BABYLON.AbstractScene",Oa);class Jh{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in Jh.Triggers)if(Object.prototype.hasOwnProperty.call(Jh.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Jh.Triggers)if(Object.prototype.hasOwnProperty.call(Jh.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Jh.Triggers)if(Object.prototype.hasOwnProperty.call(Jh.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Jh.Triggers={};class $me{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class EFe{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class Ae{static FromPromise(e,t){const i=new Ae;return e.then(r=>{i.notifyObservers(r)}).catch(r=>{if(t)t.notifyObservers(r);else throw r}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new $me(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,n=!1){if(!e)return null;const a=new EFe(e,t,r);return a.unregisterOnNextCall=n,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,n){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const a=this._eventState;a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=n;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?a.lastReturnValue=o.callback.apply(o.scope,[e,a]):a.lastReturnValue=o.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new Ae;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const tP=1/2.2,zB=2.2,Co=(1+Math.sqrt(5))/2,ci=.001;function vh(s,e){const t=[];for(let i=0;i{const n=r.previous;if(!n)return;const a=r.next;a?(n.next=a,a.previous=n):(n.next=void 0,s[e]=n),r.next=void 0,r.previous=void 0}}const Z1t=["push","splice","pop","shift","unshift"];function TFe(s,e){const t=Z1t.map(i=>$1t(s,i,e));return()=>{t.forEach(i=>{i==null||i()})}}class al{static SetMatrixPrecision(e){if(al.MatrixTrackPrecisionChange=!1,e&&!al.MatrixUse64Bits&&al.MatrixTrackedMatrices)for(let t=0;tparseInt(s.toString().replace(/\W/g,""));class we{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){const e=td(this.x),t=td(this.y);let i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return we.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new we(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new we(this.x+e.x,this.y+e.y)}subtract(e){return new we(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new we(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new we(this.x*e,this.y*t)}divide(e){return new we(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new we(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new we(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new we(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=ci){return e&&Dc(this.x,e.x,t)&&Dc(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new we(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new we(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),r=Math.sin(e),n=i*this.x-r*this.y,a=r*this.x+i*this.y;return t.x=n,t.y=a,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new we;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new we(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new we(0,0)}static One(){return new we(1,1)}static Random(e=0,t=1){return new we(Es(e,t),Es(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Es(e,t),Es(e,t))}static get ZeroReadOnly(){return we._ZeroReadOnly}static FromArray(e,t=0){return new we(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,n){const a=n*n,o=n*a,l=.5*(2*t.x+(-e.x+i.x)*n+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*o),c=.5*(2*t.y+(-e.y+i.y)*n+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*o);return new we(l,c)}static ClampToRef(e,t,i,r){return r.x=sa(e.x,t.x,i.x),r.y=sa(e.y,t.y,i.y),r}static Clamp(e,t,i){const r=sa(e.x,t.x,i.x),n=sa(e.y,t.y,i.y);return new we(r,n)}static Hermite(e,t,i,r,n){const a=n*n,o=n*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+n,h=o-a,d=e.x*l+i.x*c+t.x*u+r.x*h,f=e.y*l+i.y*c+t.y*u+r.y*h;return new we(d,f)}static Hermite1stDerivative(e,t,i,r,n){return this.Hermite1stDerivativeToRef(e,t,i,r,n,new we)}static Hermite1stDerivativeToRef(e,t,i,r,n,a){const o=n*n;return a.x=(o-n)*6*e.x+(3*o-4*n+1)*t.x+(-o+n)*6*i.x+(3*o-2*n)*r.x,a.y=(o-n)*6*e.y+(3*o-4*n+1)*t.y+(-o+n)*6*i.y+(3*o-2*n)*r.y,a}static Lerp(e,t,i){return we.LerpToRef(e,t,i,new we)}static LerpToRef(e,t,i,r){return r.x=e.x+(t.x-e.x)*i,r.y=e.y+(t.y-e.y)*i,r}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return we.NormalizeToRef(e,new we)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new we(i,r)}static Transform(e,t){return we.TransformToRef(e,t,new we)}static TransformToRef(e,t,i){const r=t.m,n=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=n,i.y=a,i}static PointInTriangle(e,t,i,r){const n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=n<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return o>0&&l>0&&o+l<2*n*a}static Distance(e,t){return Math.sqrt(we.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){return we.CenterToRef(e,t,new we)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const r=we.DistanceSquared(t,i);if(r===0)return we.Distance(e,t);const n=i.subtract(t),a=Math.max(0,Math.min(1,we.Dot(e.subtract(t),n)/r)),o=t.add(n.multiplyByFloats(a,a));return we.Distance(e,o)}}we._ZeroReadOnly=we.Zero();Object.defineProperties(we.prototype,{dimension:{value:[2]},rank:{value:1}});class D{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){const e=td(this._x),t=td(this._y),i=td(this._z);let r=e;return r=r*397^t,r=r*397^i,r}asArray(){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,this}fromArray(e,t=0){return D.FromArrayToRef(e,t,this),this}toQuaternion(){return Pe.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new D(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new D(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new D(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._isDirty=!0,r}negate(){return new D(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=this._x*-1,e._y=this._y*-1,e._z=this._z*-1,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new D(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const n=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(n,a,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,r=this._y,n=this._z,a=e._x,o=e._y,l=e._z,c=e._w,u=2*(o*n-l*r),h=2*(l*i-a*n),d=2*(a*r-o*i);return t._x=i+c*u+o*d-l*h,t._y=r+c*h+l*u-a*d,t._z=n+c*d+a*h-o*u,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new D)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new D)}projectOnPlaneToRef(e,t,i){const r=e.normal,n=e.d,a=$t.Vector3[0];this.subtractToRef(t,a),a.normalize();const o=D.Dot(a,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const l=-(D.Dot(t,r)+n)/o,c=a.scaleInPlace(l);t.addToRef(c,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=ci){return e&&Dc(this._x,e._x,t)&&Dc(this._y,e._y,t)&&Dc(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new D(this._x*e,this._y*t,this._z*i)}divide(e){return new D(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!Dc(t,i,e))return!0;const r=Math.abs(this._z);return!Dc(t,r,e)||!Dc(i,r,e)}get isNonUniform(){const e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;const i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new D(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new D(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=$t.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix($t.Matrix[0]),D.TransformCoordinatesToRef(this,$t.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,$t.Vector3[0]),$t.Vector3[0].rotateByQuaternionToRef(e,$t.Vector3[0]),t.addToRef($t.Vector3[0],i),i}cross(e){return D.CrossToRef(this,e,new D)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new D)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new D(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){const n=D.Dot(e,i),a=D.Dot(t,i);return(n-r)/(n-a)}static GetAngleBetweenVectors(e,t,i){const r=e.normalizeToRef($t.Vector3[1]),n=t.normalizeToRef($t.Vector3[2]);let a=D.Dot(r,n);a=sa(a,-1,1);const o=Math.acos(a),l=$t.Vector3[3];return D.CrossToRef(r,n,l),D.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){$t.Vector3[0].copyFrom(e);const r=$t.Vector3[0];$t.Vector3[1].copyFrom(t);const n=$t.Vector3[1];$t.Vector3[2].copyFrom(i);const a=$t.Vector3[2],o=$t.Vector3[3],l=$t.Vector3[4];r.normalize(),n.normalize(),a.normalize(),D.CrossToRef(a,r,o),D.CrossToRef(o,a,l);const c=Math.atan2(D.Dot(n,o),D.Dot(n,l));return MFe(c)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const r=se.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=D.Zero();return D.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){i=sa(i,0,1);const n=$t.Vector3[0],a=$t.Vector3[1];n.copyFrom(e);const o=n.length();n.normalizeFromLength(o),a.copyFrom(t);const l=a.length();a.normalizeFromLength(l);const c=D.Dot(n,a);let u,h;if(c<1-ci){const d=Math.acos(c),f=1/Math.sin(d);u=Math.sin((1-i)*d)*f,h=Math.sin(i*d)*f}else u=1-i,h=i;return n.scaleInPlace(u),a.scaleInPlace(h),r.copyFrom(n).addInPlace(a),r.scaleInPlace(Md(o,l,i)),r}static SmoothToRef(e,t,i,r,n){return D.SlerpToRef(e,t,r===0?1:i/r,n),n}static FromArray(e,t=0){return new D(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return D.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return D.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new D(0,0,0)}static One(){return new D(1,1,1)}static Up(){return new D(0,1,0)}static get UpReadOnly(){return D._UpReadOnly}static get DownReadOnly(){return D._DownReadOnly}static get RightReadOnly(){return D._RightReadOnly}static get LeftReadOnly(){return D._LeftReadOnly}static get LeftHandedForwardReadOnly(){return D._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return D._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return D._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return D._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return D._ZeroReadOnly}static get OneReadOnly(){return D._OneReadOnly}static Down(){return new D(0,-1,0)}static Forward(e=!1){return new D(0,0,e?-1:1)}static Backward(e=!1){return new D(0,0,e?1:-1)}static Right(){return new D(1,0,0)}static Left(){return new D(-1,0,0)}static Random(e=0,t=1){return new D(Es(e,t),Es(e,t),Es(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Es(e,t),Es(e,t),Es(e,t))}static TransformCoordinates(e,t){const i=D.Zero();return D.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return D.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,n){const a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],u=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return n._x=o*u,n._y=l*u,n._z=c*u,n._isDirty=!0,n}static TransformNormal(e,t){const i=D.Zero();return D.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,n){const a=r.m;return n._x=e*a[0]+t*a[4]+i*a[8],n._y=e*a[1]+t*a[5]+i*a[9],n._z=e*a[2]+t*a[6]+i*a[10],n._isDirty=!0,n}static CatmullRom(e,t,i,r,n){const a=n*n,o=n*a,l=.5*(2*t._x+(-e._x+i._x)*n+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*o),c=.5*(2*t._y+(-e._y+i._y)*n+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*o),u=.5*(2*t._z+(-e._z+i._z)*n+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*o);return new D(l,c,u)}static Clamp(e,t,i){const r=new D;return D.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let n=e._x;n=n>i._x?i._x:n,n=ni._y?i._y:a,a=ai._z?i._z:o,o=o0&&P<0?(R.copyFrom(a),I=t,L=i):P>0&&M<0?(R.copyFrom(l),I=i,L=r):(R.copyFrom(o).scaleInPlace(-1),I=r,L=t);const k=$t.Vector3[9],V=$t.Vector3[4];if(I.subtractToRef(y,b),L.subtractToRef(y,k),D.CrossToRef(b,k,V),!(D.Dot(V,c)<0))return n.copyFrom(y),Math.abs(m*g);const j=$t.Vector3[5];D.CrossToRef(R,V,j),j.normalize();const z=$t.Vector3[9];z.copyFrom(I).subtractInPlace(y);const K=z.length();if(Kthis.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}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(r,this.w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(r,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new mt(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new mt(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new mt)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new D(this.x,this.y,this.z)}clone(){return new mt(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new mt(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return mt.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,n){return n.x=e,n.y=t,n.z=i,n.w=r,n}static Zero(){return new mt(0,0,0,0)}static One(){return new mt(1,1,1,1)}static Random(e=0,t=1){return new mt(Es(e,t),Es(e,t),Es(e,t),Es(e,t))}static RandomToRef(e=0,t=1,i){return i.x=Es(e,t),i.y=Es(e,t),i.z=Es(e,t),i.w=Es(e,t),i}static Clamp(e,t,i){return mt.ClampToRef(e,t,i,new mt)}static ClampToRef(e,t,i,r){return r.x=sa(e.x,t.x,i.x),r.y=sa(e.y,t.y,i.y),r.z=sa(e.z,t.z,i.z),r.w=sa(e.w,t.w,i.w),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return mt._ZeroReadOnly}static Normalize(e){return mt.NormalizeToRef(e,new mt)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new mt;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new mt;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(mt.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,a=e.w-t.w;return i*i+r*r+n*n+a*a}static Center(e,t){return mt.CenterToRef(e,t,new mt)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return mt.TransformCoordinatesToRef(e,t,new mt)}static TransformCoordinatesToRef(e,t,i){return mt.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,n){const a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],u=e*a[3]+t*a[7]+i*a[11]+a[15];return n.x=o,n.y=l,n.z=c,n.w=u,n}static TransformNormal(e,t){return mt.TransformNormalToRef(e,t,new mt)}static TransformNormalToRef(e,t,i){const r=t.m,n=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=n,i.y=a,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,n,a){const o=n.m;return a.x=e*o[0]+t*o[4]+i*o[8],a.y=e*o[1]+t*o[5]+i*o[9],a.z=e*o[2]+t*o[6]+i*o[10],a.w=r,a}static FromVector3(e,t=0){return new mt(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}mt._ZeroReadOnly=mt.Zero();Object.defineProperties(mt.prototype,{dimension:{value:[4]},rank:{value:1}});class Pe{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=td(this._x),t=td(this._y),i=td(this._z),r=td(this._w);let n=e;return n=n*397^t,n=n*397^i,n=n*397^r,n}asArray(){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,this}fromArray(e,t=0){return Pe.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=ci){return e&&Dc(this._x,e._x,t)&&Dc(this._y,e._y,t)&&Dc(this._z,e._z,t)&&Dc(this._w,e._w,t)}clone(){return new Pe(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new Pe(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new Pe)}subtractFromFloatsToRef(e,t,i,r,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._w=this._w-r,n._isDirty=!0,n}subtract(e){return new Pe(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new Pe(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new Pe(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,n=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,n,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new Pe)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new Pe(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new Pe(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=D.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,r=this._y,n=this._w,a=r*t-i*n,o=.4999999;if(a<-o)e._y=2*Math.atan2(r,n),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>o)e._y=2*Math.atan2(r,n),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=n*n,c=t*t,u=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*n),-c-u+h+l),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*n),c-u-h+l),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,r=this._y,n=this._w,a=Math.sqrt(i*i+r*r),o=Math.sqrt(t*t+n*n),l=2*Math.atan2(a,o),c=2*Math.atan2(t,n),u=2*Math.atan2(r,i),h=(c+u)/2,d=(c-u)/2;return e.set(d,l,h),e}toRotationMatrix(e){return he.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return Pe.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new Pe;return Pe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,r=i[0],n=i[4],a=i[8],o=i[1],l=i[5],c=i[9],u=i[2],h=i[6],d=i[10],f=r+l+d;let p;return f>0?(p=.5/Math.sqrt(f+1),t._w=.25/p,t._x=(h-c)*p,t._y=(a-u)*p,t._z=(o-n)*p,t._isDirty=!0):r>l&&r>d?(p=2*Math.sqrt(1+r-l-d),t._w=(h-c)/p,t._x=.25*p,t._y=(n+o)/p,t._z=(a+u)/p,t._isDirty=!0):l>d?(p=2*Math.sqrt(1+l-r-d),t._w=(a-u)/p,t._x=(n+o)/p,t._y=.25*p,t._z=(c+h)/p,t._isDirty=!0):(p=2*Math.sqrt(1+d-r-l),t._w=(o-n)/p,t._x=(a+u)/p,t._y=(c+h)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const r=Pe.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,n){let a=r===0?1:i/r;return a=sa(a,0,1),Pe.SlerpToRef(e,t,a,n),n}static Zero(){return new Pe(0,0,0,0)}static Inverse(e){return new Pe(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new Pe(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return Pe.RotationAxisToRef(e,t,new Pe)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const r=Math.sin(t/2)/e.length();return i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new Pe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,n){return n.copyFromFloats(e,t,i,r),n}static FromEulerAngles(e,t,i){const r=new Pe;return Pe.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return Pe.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){const t=new Pe;return Pe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return Pe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=ci){const n=D.Dot(e,t)+1;return nMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(D.CrossToRef(e,t,se.Vector3[0]),i.set(se.Vector3[0].x,se.Vector3[0].y,se.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const r=new Pe;return Pe.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){const n=i*.5,a=t*.5,o=e*.5,l=Math.sin(n),c=Math.cos(n),u=Math.sin(a),h=Math.cos(a),d=Math.sin(o),f=Math.cos(o);return r._x=f*u*c+d*h*l,r._y=d*h*c-f*u*l,r._z=f*h*l-d*u*c,r._w=f*h*c+d*u*l,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){const r=new Pe;return Pe.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){const n=(i+e)*.5,a=(i-e)*.5,o=t*.5;return r._x=Math.cos(a)*Math.sin(o),r._y=Math.sin(a)*Math.sin(o),r._z=Math.sin(n)*Math.cos(o),r._w=Math.cos(n)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){const r=new Pe(0,0,0,0);return Pe.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){const n=$t.Matrix[0];return e=e.normalizeToRef($t.Vector3[0]),t=t.normalizeToRef($t.Vector3[1]),i=i.normalizeToRef($t.Vector3[2]),he.FromXYZAxesToRef(e,t,i,n),Pe.FromRotationMatrixToRef(n,r),r}static FromLookDirectionLH(e,t){const i=new Pe;return Pe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const r=$t.Matrix[0];return he.LookDirectionLHToRef(e,t,r),Pe.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){const i=new Pe;return Pe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const r=$t.Matrix[0];return he.LookDirectionRHToRef(e,t,r),Pe.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){const r=Pe.Identity();return Pe.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let n,a,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)a=1-i,n=l?-i:i;else{const c=Math.acos(o),u=1/Math.sin(c);a=Math.sin((1-i)*c)*u,n=l?-Math.sin(i*c)*u:Math.sin(i*c)*u}return r._x=a*e._x+n*t._x,r._y=a*e._y+n*t._y,r._z=a*e._z+n*t._z,r._w=a*e._w+n*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,n){const a=n*n,o=n*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+n,h=o-a,d=e._x*l+i._x*c+t._x*u+r._x*h,f=e._y*l+i._y*c+t._y*u+r._y*h,p=e._z*l+i._z*c+t._z*u+r._z*h,m=e._w*l+i._w*c+t._w*u+r._w*h;return new Pe(d,f,p,m)}static Hermite1stDerivative(e,t,i,r,n){const a=new Pe;return this.Hermite1stDerivativeToRef(e,t,i,r,n,a),a}static Hermite1stDerivativeToRef(e,t,i,r,n,a){const o=n*n;return a._x=(o-n)*6*e._x+(3*o-4*n+1)*t._x+(-o+n)*6*i._x+(3*o-2*n)*r._x,a._y=(o-n)*6*e._y+(3*o-4*n+1)*t._y+(-o+n)*6*i._y+(3*o-2*n)*r._y,a._z=(o-n)*6*e._z+(3*o-4*n+1)*t._z+(-o+n)*6*i._z+(3*o-2*n)*r._z,a._w=(o-n)*6*e._w+(3*o-4*n+1)*t._w+(-o+n)*6*i._w+(3*o-2*n)*r._w,a._isDirty=!0,a}static Normalize(e){const t=Pe.Zero();return Pe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const r=new Pe;return Pe.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats(sa(e.x,t.x,i.x),sa(e.y,t.y,i.y),sa(e.z,t.z,i.z),sa(e.w,t.w,i.w))}static Random(e=0,t=1){return new Pe(Es(e,t),Es(e,t),Es(e,t),Es(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Es(e,t),Es(e,t),Es(e,t),Es(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(Pe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,a=e.w-t.w;return i*i+r*r+n*n+a*a}static Center(e,t){return Pe.CenterToRef(e,t,Pe.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(Pe.prototype,{dimension:{value:[4]},rank:{value:1}});class he{static get Use64Bits(){return al.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=he._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,al.MatrixTrackPrecisionChange&&al.MatrixTrackedMatrices.push(this),this._m=new al.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=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}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;const e=this._m,t=e[0],i=e[1],r=e[2],n=e[3],a=e[4],o=e[5],l=e[6],c=e[7],u=e[8],h=e[9],d=e[10],f=e[11],p=e[12],m=e[13],g=e[14],_=e[15],y=d*_-g*f,v=h*_-m*f,x=h*g-m*d,A=u*_-p*f,b=u*g-d*p,C=u*m-p*h,T=+(o*y-l*v+c*x),w=-(a*y-l*A+c*b),P=+(a*v-o*A+c*C),M=-(a*x-o*b+l*C);return t*T+i*w+r*P+n*M}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} ${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} ${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} ${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return he.FromArrayToRef(e,t,this)}copyFromFloats(...e){return he.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return he.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new he;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,r=t._m,n=e.m;for(let a=0;a<16;a++)r[a]=i[a]+n[a];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;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],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,r=e.m,n=t._m;for(let a=0;a<16;a++)n[a]=i[a]-r[a];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new he)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,n=e;for(let a=0;a<16;a++)r[a]=i[a]-n[a];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return he.IdentityToRef(e),e;const t=this._m,i=t[0],r=t[1],n=t[2],a=t[3],o=t[4],l=t[5],c=t[6],u=t[7],h=t[8],d=t[9],f=t[10],p=t[11],m=t[12],g=t[13],_=t[14],y=t[15],v=f*y-_*p,x=d*y-g*p,A=d*_-g*f,b=h*y-m*p,C=h*_-f*m,T=h*g-m*d,w=+(l*v-c*x+u*A),P=-(o*v-c*b+u*C),M=+(o*x-l*b+u*T),R=-(o*A-l*C+c*T),I=i*w+r*P+n*M+a*R;if(I===0)return e.copyFrom(this),e;const L=1/I,k=c*y-_*u,V=l*y-g*u,H=l*_-g*c,j=o*y-m*u,z=o*_-m*c,K=o*g-m*l,U=c*p-f*u,W=l*p-d*u,Z=l*f-d*c,q=o*p-h*u,ie=o*f-h*c,ae=o*d-h*l,ue=-(r*v-n*x+a*A),ce=+(i*v-n*b+a*C),N=-(i*x-r*b+a*T),B=+(i*A-r*C+n*T),Y=+(r*k-n*V+a*H),te=-(i*k-n*j+a*z),oe=+(i*V-r*j+a*K),ne=-(i*H-r*z+n*K),pe=-(r*U-n*W+a*Z),ye=+(i*U-n*q+a*ie),Ie=-(i*W-r*q+a*ae),Ne=+(i*Z-r*ie+n*ae);return he.FromValuesToRef(w*L,ue*L,Y*L,pe*L,P*L,ce*L,te*L,ye*L,M*L,N*L,oe*L,Ie*L,R*L,B*L,ne*L,Ne*L,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new D(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return he.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new he;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]*=i[r];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,n=e;for(let a=0;a<16;a++)r[a]=i[a]*n[a];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const r=this._m,n=e.m,a=r[0],o=r[1],l=r[2],c=r[3],u=r[4],h=r[5],d=r[6],f=r[7],p=r[8],m=r[9],g=r[10],_=r[11],y=r[12],v=r[13],x=r[14],A=r[15],b=n[0],C=n[1],T=n[2],w=n[3],P=n[4],M=n[5],R=n[6],I=n[7],L=n[8],k=n[9],V=n[10],H=n[11],j=n[12],z=n[13],K=n[14],U=n[15];return t[i]=a*b+o*P+l*L+c*j,t[i+1]=a*C+o*M+l*k+c*z,t[i+2]=a*T+o*R+l*V+c*K,t[i+3]=a*w+o*I+l*H+c*U,t[i+4]=u*b+h*P+d*L+f*j,t[i+5]=u*C+h*M+d*k+f*z,t[i+6]=u*T+h*R+d*V+f*K,t[i+7]=u*w+h*I+d*H+f*U,t[i+8]=p*b+m*P+g*L+_*j,t[i+9]=p*C+m*M+g*k+_*z,t[i+10]=p*T+m*R+g*V+_*K,t[i+11]=p*w+m*I+g*H+_*U,t[i+12]=y*b+v*P+x*L+A*j,t[i+13]=y*C+v*M+x*k+A*z,t[i+14]=y*T+v*R+x*V+A*K,t[i+15]=y*w+v*I+x*H+A*U,this}divide(e){return this.divideToRef(e,new he)}divideToRef(e,t){const i=this._m,r=e.m,n=t._m;for(let a=0;a<16;a++)n[a]=i[a]/r[a];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]/=i[r];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new he)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=-t[r];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){const i=this._m,r=e.m;for(let n=0;n<16;n++)if(!Dc(i[n],r[n],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new he)}floorToRef(e){const t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=Math.floor(t[r]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new he)}fractToRef(e){const t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=t[r]-Math.floor(t[r]);return e.markAsUpdated(),e}clone(){const e=new he;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=td(this._m[0]);for(let t=1;t<16;t++)e=e*397^td(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Pe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,n=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const a=this._m;if(i&&i.copyFromFloats(a[12],a[13],a[14]),e=e||$t.Vector3[0],e.x=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]),e.y=Math.sqrt(a[4]*a[4]+a[5]*a[5]+a[6]*a[6]),e.z=Math.sqrt(a[8]*a[8]+a[9]*a[9]+a[10]*a[10]),r){const o=(n?r.absoluteScaling.x:r.scaling.x)<0?-1:1,l=(n?r.absoluteScaling.y:r.scaling.y)<0?-1:1,c=(n?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=c}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const o=1/e._x,l=1/e._y,c=1/e._z;he.FromValuesToRef(a[0]*o,a[1]*o,a[2]*o,0,a[4]*l,a[5]*l,a[6]*l,0,a[8]*c,a[9]*c,a[10]*c,0,0,0,0,1,$t.Matrix[0]),Pe.FromRotationMatrixToRef($t.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new mt(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new he;return he.TransposeToRef(this,e),e}transposeToRef(e){return he.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,n){if(e<0||e>3)return this;const a=e*4;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=n,this.markAsUpdated(),this}scale(e){const t=new he;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=$t.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return he.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new he;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=$t.Vector3[0];if(!this.decompose(t))return he.IdentityToRef(e),e;const i=this._m,r=1/t._x,n=1/t._y,a=1/t._z;return he.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*n,i[5]*n,i[6]*n,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new he;return he.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){return r._m[0]=e[0+t]*i,r._m[1]=e[1+t]*i,r._m[2]=e[2+t]*i,r._m[3]=e[3+t]*i,r._m[4]=e[4+t]*i,r._m[5]=e[5+t]*i,r._m[6]=e[6+t]*i,r._m[7]=e[7+t]*i,r._m[8]=e[8+t]*i,r._m[9]=e[9+t]*i,r._m[10]=e[10+t]*i,r._m[11]=e[11+t]*i,r._m[12]=e[12+t]*i,r._m[13]=e[13+t]*i,r._m[14]=e[14+t]*i,r._m[15]=e[15+t]*i,r.markAsUpdated(),r}static get IdentityReadOnly(){return he._IdentityReadOnly}static FromValuesToRef(e,t,i,r,n,a,o,l,c,u,h,d,f,p,m,g,_){const y=_._m;y[0]=e,y[1]=t,y[2]=i,y[3]=r,y[4]=n,y[5]=a,y[6]=o,y[7]=l,y[8]=c,y[9]=u,y[10]=h,y[11]=d,y[12]=f,y[13]=p,y[14]=m,y[15]=g,_.markAsUpdated()}static FromValues(e,t,i,r,n,a,o,l,c,u,h,d,f,p,m,g){const _=new he,y=_._m;return y[0]=e,y[1]=t,y[2]=i,y[3]=r,y[4]=n,y[5]=a,y[6]=o,y[7]=l,y[8]=c,y[9]=u,y[10]=h,y[11]=d,y[12]=f,y[13]=p,y[14]=m,y[15]=g,_.markAsUpdated(),_}static Compose(e,t,i){const r=new he;return he.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){const n=r._m,a=t._x,o=t._y,l=t._z,c=t._w,u=a+a,h=o+o,d=l+l,f=a*u,p=a*h,m=a*d,g=o*h,_=o*d,y=l*d,v=c*u,x=c*h,A=c*d,b=e._x,C=e._y,T=e._z;return n[0]=(1-(g+y))*b,n[1]=(p+A)*b,n[2]=(m-x)*b,n[3]=0,n[4]=(p-A)*C,n[5]=(1-(f+y))*C,n[6]=(_+v)*C,n[7]=0,n[8]=(m+x)*T,n[9]=(_-v)*T,n[10]=(1-(f+g))*T,n[11]=0,n[12]=i._x,n[13]=i._y,n[14]=i._z,n[15]=1,r.markAsUpdated(),r}static Identity(){const e=he.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return he.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=he.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new he;return he.RotationXToRef(e,t),t}static Invert(e){const t=new he;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return he.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationY(e){const t=new he;return he.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return he.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationZ(e){const t=new he;return he.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return he.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationAxis(e,t){const i=new he;return he.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const r=Math.sin(-t),n=Math.cos(-t),a=1-n;e=e.normalizeToRef($t.Vector3[0]);const o=i._m;return o[0]=e._x*e._x*a+n,o[1]=e._x*e._y*a-e._z*r,o[2]=e._x*e._z*a+e._y*r,o[3]=0,o[4]=e._y*e._x*a+e._z*r,o[5]=e._y*e._y*a+n,o[6]=e._y*e._z*a-e._x*r,o[7]=0,o[8]=e._z*e._x*a-e._y*r,o[9]=e._z*e._y*a+e._x*r,o[10]=e._z*e._z*a+n,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){const n=D.Dot(t,e),a=i._m;if(n<-1+ci)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{const o=D.Cross(t,e),l=1/(1+n);a[0]=o._x*o._x*l+n,a[1]=o._y*o._x*l-o._z,a[2]=o._z*o._x*l+o._y,a[3]=0,a[4]=o._x*o._y*l+o._z,a[5]=o._y*o._y*l+n,a[6]=o._z*o._y*l-o._x,a[7]=0,a[8]=o._x*o._z*l-o._y,a[9]=o._y*o._z*l+o._x,a[10]=o._z*o._z*l+n,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const r=new he;return he.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return Pe.RotationYawPitchRollToRef(e,t,i,$t.Quaternion[0]),$t.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){const r=new he;return he.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return he.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(e===1&&t===1&&i===1),r}static Translation(e,t,i){const r=new he;return he.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return he.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(e===0&&t===0&&i===0),r}static Lerp(e,t,i){const r=new he;return he.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){const n=r._m,a=e.m,o=t.m;for(let l=0;l<16;l++)n[l]=a[l]*(1-i)+o[l]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){const r=new he;return he.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){const n=$t.Vector3[0],a=$t.Quaternion[0],o=$t.Vector3[1];e.decompose(n,a,o);const l=$t.Vector3[2],c=$t.Quaternion[1],u=$t.Vector3[3];t.decompose(l,c,u);const h=$t.Vector3[4];D.LerpToRef(n,l,i,h);const d=$t.Quaternion[2];Pe.SlerpToRef(a,c,i,d);const f=$t.Vector3[5];return D.LerpToRef(o,u,i,f),he.ComposeToRef(h,d,f,r),r}static LookAtLH(e,t,i){const r=new he;return he.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){const n=$t.Vector3[0],a=$t.Vector3[1],o=$t.Vector3[2];t.subtractToRef(e,o),o.normalize(),D.CrossToRef(i,o,n);const l=n.lengthSquared();l===0?n.x=1:n.normalizeFromLength(Math.sqrt(l)),D.CrossToRef(o,n,a),a.normalize();const c=-D.Dot(n,e),u=-D.Dot(a,e),h=-D.Dot(o,e);return he.FromValuesToRef(n._x,a._x,o._x,0,n._y,a._y,o._y,0,n._z,a._z,o._z,0,c,u,h,1,r),r}static LookAtRH(e,t,i){const r=new he;return he.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){const n=$t.Vector3[0],a=$t.Vector3[1],o=$t.Vector3[2];e.subtractToRef(t,o),o.normalize(),D.CrossToRef(i,o,n);const l=n.lengthSquared();l===0?n.x=1:n.normalizeFromLength(Math.sqrt(l)),D.CrossToRef(o,n,a),a.normalize();const c=-D.Dot(n,e),u=-D.Dot(a,e),h=-D.Dot(o,e);return he.FromValuesToRef(n._x,a._x,o._x,0,n._y,a._y,o._y,0,n._z,a._z,o._z,0,c,u,h,1,r),r}static LookDirectionLH(e,t){const i=new he;return he.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const r=$t.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);const n=$t.Vector3[1];return D.CrossToRef(t,r,n),he.FromValuesToRef(n._x,n._y,n._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new he;return he.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const r=$t.Vector3[2];return D.CrossToRef(t,e,r),he.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,n){const a=new he;return he.OrthoLHToRef(e,t,i,r,a,n),a}static OrthoLHToRef(e,t,i,r,n,a){const o=i,l=r,c=2/e,u=2/t,h=2/(l-o),d=-(l+o)/(l-o);return he.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,h,0,0,0,d,1,n),a&&n.multiplyToRef(gC,n),n._updateIdentityStatus(c===1&&u===1&&h===1&&d===0),n}static OrthoOffCenterLH(e,t,i,r,n,a,o){const l=new he;return he.OrthoOffCenterLHToRef(e,t,i,r,n,a,l,o),l}static OrthoOffCenterLHToRef(e,t,i,r,n,a,o,l){const c=n,u=a,h=2/(t-e),d=2/(r-i),f=2/(u-c),p=-(u+c)/(u-c),m=(e+t)/(e-t),g=(r+i)/(i-r);return he.FromValuesToRef(h,0,0,0,0,d,0,0,0,0,f,0,m,g,p,1,o),l&&o.multiplyToRef(gC,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,n,a,o,l,c,u,h){const d=-o*Math.cos(l),f=-o*Math.sin(l);return he.TranslationToRef(0,0,-c,$t.Matrix[1]),he.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,$t.Matrix[0]),$t.Matrix[1].multiplyToRef($t.Matrix[0],$t.Matrix[0]),he.TranslationToRef(0,0,c,$t.Matrix[1]),$t.Matrix[0].multiplyToRef($t.Matrix[1],$t.Matrix[0]),he.OrthoOffCenterLHToRef(e,t,i,r,n,a,u,h),$t.Matrix[0].multiplyToRef(u,u),u}static OrthoOffCenterRH(e,t,i,r,n,a,o){const l=new he;return he.OrthoOffCenterRHToRef(e,t,i,r,n,a,l,o),l}static OrthoOffCenterRHToRef(e,t,i,r,n,a,o,l){return he.OrthoOffCenterLHToRef(e,t,i,r,n,a,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,n,a,o,l,c,u,h){const d=o*Math.cos(l),f=o*Math.sin(l);return he.TranslationToRef(0,0,c,$t.Matrix[1]),he.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,$t.Matrix[0]),$t.Matrix[1].multiplyToRef($t.Matrix[0],$t.Matrix[0]),he.TranslationToRef(0,0,-c,$t.Matrix[1]),$t.Matrix[0].multiplyToRef($t.Matrix[1],$t.Matrix[0]),he.OrthoOffCenterRHToRef(e,t,i,r,n,a,u,h),$t.Matrix[0].multiplyToRef(u,u),u}static PerspectiveLH(e,t,i,r,n,a=0){const o=new he,l=i,c=r,u=2*l/e,h=2*l/t,d=(c+l)/(c-l),f=-2*c*l/(c-l),p=Math.tan(a);return he.FromValuesToRef(u,0,0,0,0,h,0,p,0,0,d,1,0,0,f,0,o),n&&o.multiplyToRef(gC,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,n,a=0,o=!1){const l=new he;return he.PerspectiveFovLHToRef(e,t,i,r,l,!0,n,a,o),l}static PerspectiveFovLHToRef(e,t,i,r,n,a=!0,o,l=0,c=!1){const u=i,h=r,d=1/Math.tan(e*.5),f=a?d/t:d,p=a?d:d*t,m=c&&u===0?-1:h!==0?(h+u)/(h-u):1,g=c&&u===0?2*h:h!==0?-2*h*u/(h-u):-2*u,_=Math.tan(l);return he.FromValuesToRef(f,0,0,0,0,p,0,_,0,0,m,1,0,0,g,0,n),o&&n.multiplyToRef(gC,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseLHToRef(e,t,i,r,n,a=!0,o,l=0){const c=1/Math.tan(e*.5),u=a?c/t:c,h=a?c:c*t,d=Math.tan(l);return he.FromValuesToRef(u,0,0,0,0,h,0,d,0,0,-i,1,0,0,1,0,n),o&&n.multiplyToRef(gC,n),n._updateIdentityStatus(!1),n}static PerspectiveFovRH(e,t,i,r,n,a=0,o=!1){const l=new he;return he.PerspectiveFovRHToRef(e,t,i,r,l,!0,n,a,o),l}static PerspectiveFovRHToRef(e,t,i,r,n,a=!0,o,l=0,c=!1){const u=i,h=r,d=1/Math.tan(e*.5),f=a?d/t:d,p=a?d:d*t,m=c&&u===0?1:h!==0?-(h+u)/(h-u):-1,g=c&&u===0?2*h:h!==0?-2*h*u/(h-u):-2*u,_=Math.tan(l);return he.FromValuesToRef(f,0,0,0,0,p,0,_,0,0,m,-1,0,0,g,0,n),o&&n.multiplyToRef(gC,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseRHToRef(e,t,i,r,n,a=!0,o,l=0){const c=1/Math.tan(e*.5),u=a?c/t:c,h=a?c:c*t,d=Math.tan(l);return he.FromValuesToRef(u,0,0,0,0,h,0,d,0,0,-i,-1,0,0,-1,0,n),o&&n.multiplyToRef(gC,n),n._updateIdentityStatus(!1),n}static GetFinalMatrix(e,t,i,r,n,a){const o=e.width,l=e.height,c=e.x,u=e.y,h=he.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,a-n,0,c+o/2,l/2+u,n,1),d=new he;return t.multiplyToRef(i,d),d.multiplyToRef(r,d),d.multiplyToRef(h,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return al.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return al.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new he;return he.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,r=i[0],n=i[4],a=i[8],o=i[12],l=i[1],c=i[5],u=i[9],h=i[13],d=i[2],f=i[6],p=i[10],m=i[14],g=i[3],_=i[7],y=i[11],v=i[15],x=t._m;return x[0]=r,x[1]=n,x[2]=a,x[3]=o,x[4]=l,x[5]=c,x[6]=u,x[7]=h,x[8]=d,x[9]=f,x[10]=p,x[11]=m,x[12]=g,x[13]=_,x[14]=y,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new he;return he.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,r=e.normal.y,n=e.normal.z,a=-2*i,o=-2*r,l=-2*n;return he.FromValuesToRef(a*i+1,o*i,l*i,0,a*r,o*r+1,l*r,0,a*n,o*n,l*n+1,0,a*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return he.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){const i=e._x*e._x,r=e._y*e._y,n=e._z*e._z,a=e._x*e._y,o=e._z*e._w,l=e._z*e._x,c=e._y*e._w,u=e._y*e._z,h=e._x*e._w;return t._m[0]=1-2*(r+n),t._m[1]=2*(a+o),t._m[2]=2*(l-c),t._m[3]=0,t._m[4]=2*(a-o),t._m[5]=1-2*(n+i),t._m[6]=2*(u+h),t._m[7]=0,t._m[8]=2*(l+c),t._m[9]=2*(u-h),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}he._UpdateFlagSeed=0;he._IdentityReadOnly=he.Identity();Object.defineProperties(he.prototype,{dimension:{value:[4,4]},rank:{value:2}});class $t{}$t.Vector3=Ux(11,D.Zero);$t.Matrix=Ux(2,he.Identity);$t.Quaternion=Ux(3,Pe.Zero);class se{}se.Vector2=Ux(3,we.Zero);se.Vector3=Ux(13,D.Zero);se.Vector4=Ux(3,mt.Zero);se.Quaternion=Ux(3,Pe.Zero);se.Matrix=Ux(8,he.Identity);ve("BABYLON.Vector2",we);ve("BABYLON.Vector3",D);ve("BABYLON.Vector4",mt);ve("BABYLON.Matrix",he);const gC=he.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class At{static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(e===0)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e=e*2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=At.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=At.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=At.Clamp(i);return r=-2*r*r*r+3*r*r,t*r+e*(1-r)}static MoveTowards(e,t,i){let r=0;return Math.abs(t-e)<=i?r=t:r=e+At.Sign(t-e)*i,r}static MoveTowardsAngle(e,t,i){const r=At.DeltaAngle(e,t);let n=0;return-i180&&(r-=360),e+r*sa(i)}static InverseLerp(e,t,i){let r=0;return e!=t?r=sa((i-e)/(t-e)):r=0,r}static Hermite(e,t,i,r,n){const a=n*n,o=n*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+n,h=o-a;return e*l+i*c+t*u+r*h}static Hermite1stDerivative(e,t,i,r,n){const a=n*n;return(a-n)*6*e+(3*a-4*n+1)*t+(-a+n)*6*i+(3*a-2*n)*r}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return i===0?t:At.HCF(t,i)}}At.TwoPi=Math.PI*2;At.WithinEpsilon=Dc;At.ToHex=Dm;At.Clamp=sa;At.Lerp=Md;At.RandomRange=Es;At.NormalizeRadians=MFe;function iP(s){return Math.pow(s,zB)}function rP(s){return s<=.04045?.0773993808*s:Math.pow(.947867299*(s+.055),2.4)}function sP(s){return Math.pow(s,tP)}function nP(s){return s<=.0031308?12.92*s:1.055*Math.pow(s,.41666)-.055}class Re{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Re.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ze(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new Re(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new Re(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=ci){return At.WithinEpsilon(this.r,e.r,t)&&At.WithinEpsilon(this.g,e.g,t)&&At.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Re(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=sa(this.r,e,t),i.g=sa(this.g,e,t),i.b=sa(this.b,e,t),i}add(e){return new Re(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Re(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new Re(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r}clone(){return new Re(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+Dm(e)+Dm(t)+Dm(i)}toHSV(){return this.toHSVToRef(new Re)}toHSVToRef(e){const t=this.r,i=this.g,r=this.b,n=Math.max(t,i,r),a=Math.min(t,i,r);let o=0,l=0;const c=n,u=n-a;return n!==0&&(l=u/n),n!=a&&(n==t?(o=(i-r)/u,i=0&&a<=1?(l=n,c=o):a>=1&&a<=2?(l=o,c=n):a>=2&&a<=3?(c=n,u=o):a>=3&&a<=4?(c=o,u=n):a>=4&&a<=5?(l=o,u=n):a>=5&&a<=6&&(l=n,u=o);const h=i-n;return r.r=l+h,r.g=c+h,r.b=u+h,r}static FromHSV(e,t,i){const r=new Re(0,0,0);return Re.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new Re(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return Re.FromInts(t,i,r)}static FromArray(e,t=0){return new Re(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Re(e/255,t/255,i/255)}static Lerp(e,t,i){const r=new Re(0,0,0);return Re.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,n){const a=n*n,o=n*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+n,h=o-a,d=e.r*l+i.r*c+t.r*u+r.r*h,f=e.g*l+i.g*c+t.g*u+r.g*h,p=e.b*l+i.b*c+t.b*u+r.b*h;return new Re(d,f,p)}static Hermite1stDerivative(e,t,i,r,n){const a=Re.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,n,a),a}static Hermite1stDerivativeToRef(e,t,i,r,n,a){const o=n*n;a.r=(o-n)*6*e.r+(3*o-4*n+1)*t.r+(-o+n)*6*i.r+(3*o-2*n)*r.r,a.g=(o-n)*6*e.g+(3*o-4*n+1)*t.g+(-o+n)*6*i.g+(3*o-2*n)*r.g,a.b=(o-n)*6*e.b+(3*o-4*n+1)*t.b+(-o+n)*6*i.b+(3*o-2*n)*r.b}static Red(){return new Re(1,0,0)}static Green(){return new Re(0,1,0)}static Blue(){return new Re(0,0,1)}static Black(){return new Re(0,0,0)}static get BlackReadOnly(){return Re._BlackReadOnly}static White(){return new Re(1,1,1)}static Purple(){return new Re(.5,0,.5)}static Magenta(){return new Re(1,0,1)}static Yellow(){return new Re(1,1,0)}static Gray(){return new Re(.5,.5,.5)}static Teal(){return new Re(0,1,1)}static Random(){return new Re(Math.random(),Math.random(),Math.random())}}Re._BlackReadOnly=Re.Black();Object.defineProperties(Re.prototype,{dimension:{value:[3]},rank:{value:1}});class Ze{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ze(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new Ze(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new Ze(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n.a=this.a-r,n}scale(e){return new Ze(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=sa(this.r,e,t),i.g=sa(this.g,e,t),i.b=sa(this.b,e,t),i.a=sa(this.a,e,t),i}multiply(e){return new Ze(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new Ze(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=ci){return At.WithinEpsilon(this.r,e.r,t)&&At.WithinEpsilon(this.g,e.g,t)&&At.WithinEpsilon(this.b,e.b,t)&&At.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new Ze().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),r=Math.round(this.b*255);if(e)return"#"+Dm(t)+Dm(i)+Dm(r);const n=Math.round(this.a*255);return"#"+Dm(t)+Dm(i)+Dm(r)+Dm(n)}toLinearSpace(e=!1){const t=new Ze;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=rP(this.r),e.g=rP(this.g),e.b=rP(this.b)):(e.r=iP(this.r),e.g=iP(this.g),e.b=iP(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ze;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=nP(this.r),e.g=nP(this.g),e.b=nP(this.b)):(e.r=sP(this.r),e.g=sP(this.g),e.b=sP(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Ze(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),n=e.length===9?parseInt(e.substring(7,9),16):255;return Ze.FromInts(t,i,r,n)}static Lerp(e,t,i){return Ze.LerpToRef(e,t,i,new Ze)}static LerpToRef(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r}static Hermite(e,t,i,r,n){const a=n*n,o=n*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+n,h=o-a,d=e.r*l+i.r*c+t.r*u+r.r*h,f=e.g*l+i.g*c+t.g*u+r.g*h,p=e.b*l+i.b*c+t.b*u+r.b*h,m=e.a*l+i.a*c+t.a*u+r.a*h;return new Ze(d,f,p,m)}static Hermite1stDerivative(e,t,i,r,n){const a=new Ze;return this.Hermite1stDerivativeToRef(e,t,i,r,n,a),a}static Hermite1stDerivativeToRef(e,t,i,r,n,a){const o=n*n;a.r=(o-n)*6*e.r+(3*o-4*n+1)*t.r+(-o+n)*6*i.r+(3*o-2*n)*r.r,a.g=(o-n)*6*e.g+(3*o-4*n+1)*t.g+(-o+n)*6*i.g+(3*o-2*n)*r.g,a.b=(o-n)*6*e.b+(3*o-4*n+1)*t.b+(-o+n)*6*i.b+(3*o-2*n)*r.b,a.a=(o-n)*6*e.a+(3*o-4*n+1)*t.a+(-o+n)*6*i.a+(3*o-2*n)*r.a}static FromColor3(e,t=1){return new Ze(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ze(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new Ze(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let r=0;rnew Ze(0,0,0,0));ve("BABYLON.Color3",Re);ve("BABYLON.Color4",Ze);class an{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new Ae,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const r=this._condition.serialize();return r.children.push(i),t&&t.children.push(r),r}return t&&t.children.push(i),i}}an._SerializeValueAsString=s=>typeof s=="number"?s.toString():typeof s=="boolean"?s?"true":"false":s instanceof we?s.x+", "+s.y:s instanceof D?s.x+", "+s.y+", "+s.z:s instanceof Re?s.r+", "+s.g+", "+s.b:s instanceof Ze?s.r+", "+s.g+", "+s.b+", "+s.a:s;an._GetTargetProperty=s=>({name:"target",targetType:s._isMesh?"MeshProperties":s._isLight?"LightProperties":s._isCamera?"CameraProperties":s._isMaterial?"MaterialProperties":"SceneProperties",value:s._isScene?"Scene":s.name});ve("BABYLON.Action",an);class Hn{constructor(e,t,i,r,n,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=n,this.additionalData=a}static CreateNew(e,t,i){const r=e.getScene();return new Hn(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new Hn(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new Hn(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new Hn(e,t.x,t.y,null,i,r)}}class JP{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class il extends JP{static get IsEqual(){return il._IsEqual}static get IsDifferent(){return il._IsDifferent}static get IsGreater(){return il._IsGreater}static get IsLesser(){return il._IsLesser}constructor(e,t,i,r,n=il.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=n,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case il.IsGreater:return this._effectiveTarget[this._property]>this.value;case il.IsLesser:return this._effectiveTarget[this._property]r<10?"0"+r:""+r,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const r=Array.isArray(t)?t[0]:t;if(i!==void 0&&!fe._CheckLimit(r,i))return;const n=fe._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+n,...o);const l=`
${n}

`;fe._AddLogEntry(l),fe._GenerateLimitMessage(r,e)}static get LogCache(){return fe._LogCache}static ClearLogCache(){fe._LogCache="",fe._LogLimitOutputs={},fe.errorsCount=0}static set LogLevels(e){fe.Log=fe._LogDisabled,fe.Warn=fe._LogDisabled,fe.Error=fe._LogDisabled,[fe.MessageLogLevel,fe.WarningLogLevel,fe.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];fe[i.name]=fe._LogEnabled.bind(fe,t)}})}}fe.NoneLogLevel=0;fe.MessageLogLevel=1;fe.WarningLogLevel=2;fe.ErrorLogLevel=4;fe.AllLogLevel=7;fe.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";fe._LogCache="";fe._LogLimitOutputs={};fe._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];fe.errorsCount=0;fe.Log=fe._LogEnabled.bind(fe,fe.MessageLogLevel);fe.Warn=fe._LogEnabled.bind(fe,fe.WarningLogLevel);fe.Error=fe._LogEnabled.bind(fe,fe.ErrorLogLevel);class PFe extends an{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[an._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class wFe extends an{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[an._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class DFe extends an{constructor(e,t,i,r,n){super(e,n),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[an._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:an._SerializeValueAsString(this.value)}]},e)}}class LFe extends an{constructor(e,t,i,r,n){super(e,n),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),typeof this._effectiveTarget[this._property]!="number"&&fe.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[an._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:an._SerializeValueAsString(this.value)}]},e)}}class OFe extends an{constructor(e,t,i,r,n,a){super(e,a),this.from=i,this.to=r,this.loop=n,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[an._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:an._SerializeValueAsString(this.loop)||!1}]},e)}}class NFe extends an{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[an._GetTargetProperty(this._target)]},e)}}class Zme extends an{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class FFe extends an{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e!s||s.getClassName&&s.getClassName()==="Mesh"?null:s.getClassName&&(s.getClassName()==="SubMesh"||s.getClassName()==="PhysicsBody")?s.clone(e):s.clone?s.clone():Array.isArray(s)?s.slice():t&&typeof s=="object"?{...s}:null;function q1t(s){const e=[];do Object.getOwnPropertyNames(s).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(s=Object.getPrototypeOf(s));return e}class Nl{static DeepCopy(e,t,i,r,n=!1){const a=q1t(e);for(const o of a){if(o[0]==="_"&&(!r||r.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;const l=e[o],c=typeof l;if(c!=="function")try{if(c==="object")if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0)if(typeof l[0]=="object")for(let u=0;u-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter(i=>i.actionManager===this);for(const i of t)i.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=hs.OnPickTrigger&&t.trigger<=hs.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=hs.OnPickTrigger&&t.trigger<=hs.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===hs.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(fe.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,hs.Triggers[e.trigger]?hs.Triggers[e.trigger]++:hs.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return t!==-1?(this.actions.splice(t,1),hs.Triggers[e.trigger]-=1,hs.Triggers[e.trigger]===0&&delete hs.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const u=Xn("BABYLON."+l);return u&&new u(...c)},a=(l,c,u,h)=>{if(h===null){const m=parseFloat(c);return c==="true"||c==="false"?c==="true":isNaN(m)?c:m}const d=h.split("."),f=c.split(",");for(let m=0;m{if(l.detached)return;const f=[];let p=null,m=null;const g=l.combine&&l.combine.length>0;if(l.type===2?f.push(r):f.push(c),g){const y=[];for(let v=0;v0){const h=u.properties[0].value,d=u.properties[0].targetType===null?h:i.getMeshByName(h);d._meshId&&(d.mesh=i.getMeshById(d._meshId)),c={trigger:hs[u.name],parameter:d}}else c=hs[u.name];for(let h=0;h=0;o--)(a=s[o])&&(n=(r<3?a(n):r>3?a(e,t,n):a(e,t))||n);return r>3&&n&&Object.defineProperty(e,t,n),n}const nY={},HQ={};function J1t(s){const e=s.getClassName();return HQ[e]||(HQ[e]={}),HQ[e]}function uue(s){const e=s.getClassName();if(nY[e])return nY[e];nY[e]={};const t=nY[e];let i=s,r=e;for(;r;){const n=HQ[r];for(const l in n)t[l]=n[l];let a,o=!1;do{if(a=Object.getPrototypeOf(i),!a.getClassName){o=!0;break}if(a.getClassName()!==r)break;i=a}while(a);if(o)break;r=a.getClassName(),i=a}return t}function ap(s,e){return(t,i)=>{const r=J1t(t);r[i]||(r[i]={type:s,sourceName:e})}}function e_t(s,e=null){return(t,i)=>{const r=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[r]},set:function(n){typeof this.equals=="function"&&this.equals(n)||this[r]!==n&&(this[r]=n,t[s].apply(this))},enumerable:!0,configurable:!0})}}function Fe(s,e=null){return e_t(s,e)}function X(s){return ap(0,s)}function ii(s){return ap(1,s)}function br(s){return ap(2,s)}function Kw(s){return ap(3,s)}function nz(s){return ap(4,s)}function Pn(s){return ap(5,s)}function Hw(s){return ap(6,s)}function zFe(s){return ap(7,s)}function jw(s){return ap(8,s)}function Jme(s){return ap(9,s)}function VFe(s){return ap(10,s)}function xJ(s){return ap(12,s)}function GFe(s){return ap(11,s)}function l_(s,e,t,i){const r=t.value;t.value=(...n)=>{let a=r;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?a=(...l)=>i(...l)?o(...l):r(...l):a=o}return s[e]=a,a(...n)}}l_.filter=function(s){return(e,t,i)=>l_(e,t,i,s)};const fTe={};function vi(s,e=!1){if(!(e&&fTe[s]))return fTe[s]=!0,`${s} needs to be imported before as it contains a side-effect required by your code.`}class wy{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),wy._HandleParenthesisContent(i,t))):e=wy._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:wy.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(n=>n==="true");let i;const r=e.split("||");for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){let a=wy._SimplifyNegation(r[n].trim());const o=a.split("&&");if(o.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class Br{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Br.HasTags(e),e.addTags=t=>Br.AddTagsTo(e,t),e.removeTags=t=>Br.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Br.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const i=[];for(const r in e._tags)Object.prototype.hasOwnProperty.call(e._tags,r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(r){Br._AddTagTo(e,r)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Br.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Br.HasTags(e))return;const i=t.split(" ");for(const r in i)Br._RemoveTagFrom(e,i[r])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?Br.HasTags(e):wy.Eval(t,i=>Br.HasTags(e)&&e._tags[i])}}const pTe=function(s,e,t,i={}){const r=s();Br&&Br.HasTags(e)&&Br.AddTagsTo(r,Br.GetTags(e,!0));const n=uue(r),a={};for(const o in n){const l=n[o],c=e[o],u=l.type;if(c!=null&&(o!=="uniqueId"||qe.AllowLoadingUniqueId))switch(u){case 0:case 6:case 11:r[o]=c;break;case 1:i.cloneTexturesOnlyOnce&&a[c.uniqueId]?r[o]=a[c.uniqueId]:(r[o]=t||c.isRenderTarget?c:c.clone(),a[c.uniqueId]=r[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[o]=t?c:c.clone();break}}return r};class qe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw vi("ImageProcessingConfiguration")};qe._FresnelParametersParser=s=>{throw vi("FresnelParameters")};qe._ColorCurvesParser=s=>{throw vi("ColorCurves")};qe._TextureParser=(s,e,t)=>{throw vi("Texture")};class t_t{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new Ae,this._onClonedObservable=new Ae}}let ns=class hue{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){const n=this._NodeConstructors[e];return n?n(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){const i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new t_t,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new Ae,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=he.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new Ae,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Rt.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){const t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children&&this._children.forEach(e=>{e._syncParentEnabledState()})}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r(!t||t(r))&&r.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew hue(e,this.getScene()),this);if(t&&(r.parent=t),!i){const n=this.getDescendants(!0);for(let a=0;a{throw vi("AnimationRange")};ns._NodeConstructors={};F([X()],ns.prototype,"name",void 0);F([X()],ns.prototype,"id",void 0);F([X()],ns.prototype,"uniqueId",void 0);F([X()],ns.prototype,"state",void 0);F([X()],ns.prototype,"metadata",void 0);class iu{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new iu(this.width*e,this.height*t)}clone(){return new iu(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new iu(0,0)}add(e){return new iu(this.width+e.width,this.height+e.height)}subtract(e){return new iu(this.width-e.width,this.height-e.height)}scale(e){return new iu(this.width*e,this.height*e)}static Lerp(e,t,i){const r=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new iu(r,n)}}function i_t(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class On{constructor(){this._xhr=i_t(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(On.CustomRequestHeaders).length>0||On.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in On.CustomRequestHeaders){const t=On.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return On.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){On.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of On.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}t=t.replace("file:http:","http:"),t=t.replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}On.CustomRequestHeaders={};On.CustomRequestModifiers=new Array;On.SkipRequestModificationForBabylonCDN=!0;const ege=Object.freeze(new Pe(0,0,0,0)),tge=Object.freeze(D.Zero()),ige=Object.freeze(we.Zero()),rge=Object.freeze(iu.Zero()),sge=Object.freeze(Re.Black()),nge=Object.freeze(new Ze(0,0,0,0)),vm={key:0,repeatCount:0,loopMode:2};let tt=class ai{static _PrepareAnimation(e,t,i,r,n,a,o,l){let c;if(!isNaN(parseFloat(n))&&isFinite(n)?c=ai.ANIMATIONTYPE_FLOAT:n instanceof Pe?c=ai.ANIMATIONTYPE_QUATERNION:n instanceof D?c=ai.ANIMATIONTYPE_VECTOR3:n instanceof we?c=ai.ANIMATIONTYPE_VECTOR2:n instanceof Re?c=ai.ANIMATIONTYPE_COLOR3:n instanceof Ze?c=ai.ANIMATIONTYPE_COLOR4:n instanceof iu&&(c=ai.ANIMATIONTYPE_SIZE),c==null)return null;const u=new ai(e,t,i,c,o),h=[{frame:0,value:n},{frame:r,value:a}];return u.setKeys(h),l!==void 0&&u.setEasingFunction(l),u}static CreateAnimation(e,t,i,r){const n=new ai(e+"Animation",e,i,t,ai.ANIMATIONLOOPMODE_CONSTANT);return n.setEasingFunction(r),n}static CreateAndStartAnimation(e,t,i,r,n,a,o,l,c,u,h){const d=ai._PrepareAnimation(e,i,r,n,a,o,l,c);return!d||(t.getScene&&(h=t.getScene()),!h)?null:h.beginDirectAnimation(t,[d],0,n,d.loopMode===1,1,u)}static CreateAndStartHierarchyAnimation(e,t,i,r,n,a,o,l,c,u,h){const d=ai._PrepareAnimation(e,r,n,a,o,l,c,u);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,a,d.loopMode===1,1,h):null}static CreateMergeAndStartAnimation(e,t,i,r,n,a,o,l,c,u){const h=ai._PrepareAnimation(e,i,r,n,a,o,l,c);return h?(t.animations.push(h),t.getScene().beginAnimation(t,0,n,h.loopMode===1,1,u)):null}static MakeAnimationAdditive(e,t,i,r=!1,n){let a;typeof t=="object"?a=t:a={referenceFrame:t??0,range:i,cloneOriginalAnimation:r,clonedAnimationName:n};let o=e;if(a.cloneOriginalAnimation&&(o=e.clone(),o.name=a.clonedAnimationName||o.name),!o._keys.length)return o;const l=a.referenceFrame&&a.referenceFrame>=0?a.referenceFrame:0;let c=0;const u=o._keys[0];let h=o._keys.length-1;const d=o._keys[h],f={referenceValue:u.value,referencePosition:se.Vector3[0],referenceQuaternion:se.Quaternion[0],referenceScaling:se.Vector3[1],keyPosition:se.Vector3[2],keyQuaternion:se.Quaternion[1],keyScaling:se.Vector3[3]};let p=u.frame,m=d.frame;if(a.range){const y=o.getRange(a.range);y&&(p=y.from,m=y.to)}else p=a.fromFrame??p,m=a.toFrame??m;if(p!==u.frame&&(c=o.createKeyForFrame(p)),m!==d.frame&&(h=o.createKeyForFrame(m)),o._keys.length===1){const y=o._getKeyValue(o._keys[0]);f.referenceValue=y.clone?y.clone():y}else if(l<=u.frame){const y=o._getKeyValue(u.value);f.referenceValue=y.clone?y.clone():y}else if(l>=d.frame){const y=o._getKeyValue(d.value);f.referenceValue=y.clone?y.clone():y}else{vm.key=0;const y=o._interpolate(l,vm);f.referenceValue=y.clone?y.clone():y}o.dataType===ai.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():o.dataType===ai.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE;const _=a.clipKeys?[]:null;for(let y=c;y<=h;y++){let v=o._keys[y];if((_||a.cloneOriginalAnimation)&&(v={frame:v.frame,value:v.value.clone?v.value.clone():v.value,inTangent:v.inTangent,outTangent:v.outTangent,interpolation:v.interpolation,lockedTangent:v.lockedTangent},_&&(g===Number.MAX_VALUE&&(g=v.frame),v.frame-=g,_.push(v))),!(y&&o.dataType!==ai.ANIMATIONTYPE_FLOAT&&v.value===u.value))switch(o.dataType){case ai.ANIMATIONTYPE_MATRIX:v.value.decompose(f.keyScaling,f.keyQuaternion,f.keyPosition),f.keyPosition.subtractInPlace(f.referencePosition),f.keyScaling.divideInPlace(f.referenceScaling),f.referenceQuaternion.multiplyToRef(f.keyQuaternion,f.keyQuaternion),he.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,v.value);break;case ai.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(v.value,v.value);break;case ai.ANIMATIONTYPE_VECTOR2:case ai.ANIMATIONTYPE_VECTOR3:case ai.ANIMATIONTYPE_COLOR3:case ai.ANIMATIONTYPE_COLOR4:v.value.subtractToRef(f.referenceValue,v.value);break;case ai.ANIMATIONTYPE_SIZE:v.value.width-=f.referenceValue.width,v.value.height-=f.referenceValue.height;break;default:v.value-=f.referenceValue}}return _&&o.setKeys(_,!0),o}static TransitionTo(e,t,i,r,n,a,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const c=n*(o/1e3);a.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:c,value:t}]),i.animations||(i.animations=[]),i.animations.push(a);const u=r.beginAnimation(i,0,c,!1);return u.onAnimationEnd=l,u}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,n,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=n,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=n===void 0?ai.ANIMATIONLOOPMODE_CYCLE:n,this.uniqueId=ai._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(const r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;a--)this._keys[a].frame>=r&&this._keys[a].frame<=n&&this._keys.splice(a,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const r=this._keys,n=r.length;let a=t.key;for(;a>=0&&e=r[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(r[0].value);if(a+1>n-1)return i?void 0:this._getKeyValue(r[n-1].value);const o=r[a],l=r[a+1];if(i&&(e===o.frame||e===l.frame))return;const c=this._getKeyValue(o.value),u=this._getKeyValue(l.value);if(o.interpolation===1)return l.frame>e?c:u;const h=o.outTangent!==void 0&&l.inTangent!==void 0,d=l.frame-o.frame;let f=(e-o.frame)/d;const p=o.easingFunction||this.getEasingFunction();switch(p!==null&&(f=p.ease(f)),this.dataType){case ai.ANIMATIONTYPE_FLOAT:{const m=h?this.floatInterpolateFunctionWithTangents(c,o.outTangent*d,u,l.inTangent*d,f):this.floatInterpolateFunction(c,u,f);switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return m;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+m}break}case ai.ANIMATIONTYPE_QUATERNION:{const m=h?this.quaternionInterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.quaternionInterpolateFunction(c,u,f);switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return m;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return m.addInPlace((t.offsetValue||ege).scale(t.repeatCount))}return m}case ai.ANIMATIONTYPE_VECTOR3:{const m=h?this.vector3InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.vector3InterpolateFunction(c,u,f);switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return m;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return m.add((t.offsetValue||tge).scale(t.repeatCount))}break}case ai.ANIMATIONTYPE_VECTOR2:{const m=h?this.vector2InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.vector2InterpolateFunction(c,u,f);switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return m;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return m.add((t.offsetValue||ige).scale(t.repeatCount))}break}case ai.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(c,u,f);case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(c,u,f).add((t.offsetValue||rge).scale(t.repeatCount))}break}case ai.ANIMATIONTYPE_COLOR3:{const m=h?this.color3InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.color3InterpolateFunction(c,u,f);switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return m;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return m.add((t.offsetValue||sge).scale(t.repeatCount))}break}case ai.ANIMATIONTYPE_COLOR4:{const m=h?this.color4InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.color4InterpolateFunction(c,u,f);switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return m;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return m.add((t.offsetValue||nge).scale(t.repeatCount))}break}case ai.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case ai.ANIMATIONLOOPMODE_CYCLE:case ai.ANIMATIONLOOPMODE_CONSTANT:case ai.ANIMATIONLOOPMODE_YOYO:return ai.AllowMatricesInterpolation?this.matrixInterpolateFunction(c,u,f,t.workValue):c;case ai.ANIMATIONLOOPMODE_RELATIVE:case ai.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return c}break}}return 0}matrixInterpolateFunction(e,t,i,r){return ai.AllowMatrixDecomposeForInterpolation?r?(he.DecomposeLerpToRef(e,t,i,r),r):he.DecomposeLerp(e,t,i):r?(he.LerpToRef(e,t,i,r),r):he.Lerp(e,t,i)}clone(){const e=new ai(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){vm.key=0;const t=this._interpolate(e,vm,!0);if(!t)return this._keys[vm.key].frame===e?vm.key:vm.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(vm.key+1,0,i),vm.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let r=0;r=2&&(l=o.values[1]),o.values.length>=3&&(c=o.values[2]),o.values.length>=4&&(u=o.values[3]);break;case ai.ANIMATIONTYPE_QUATERNION:if(n=Pe.FromArray(o.values),o.values.length>=8){const d=Pe.FromArray(o.values.slice(4,8));d.equals(Pe.Zero())||(l=d)}if(o.values.length>=12){const d=Pe.FromArray(o.values.slice(8,12));d.equals(Pe.Zero())||(c=d)}o.values.length>=13&&(u=o.values[12]);break;case ai.ANIMATIONTYPE_MATRIX:n=he.FromArray(o.values),o.values.length>=17&&(u=o.values[16]);break;case ai.ANIMATIONTYPE_COLOR3:n=Re.FromArray(o.values),o.values[3]&&(l=Re.FromArray(o.values[3])),o.values[4]&&(c=Re.FromArray(o.values[4])),o.values[5]&&(u=o.values[5]);break;case ai.ANIMATIONTYPE_COLOR4:n=Ze.FromArray(o.values),o.values[4]&&(l=Ze.FromArray(o.values[4])),o.values[5]&&(c=Ze.FromArray(o.values[5])),o.values[6]&&(u=Ze.FromArray(o.values[6]));break;case ai.ANIMATIONTYPE_VECTOR3:default:n=D.FromArray(o.values),o.values[3]&&(l=D.FromArray(o.values[3])),o.values[4]&&(c=D.FromArray(o.values[4])),o.values[5]&&(u=o.values[5]);break}const h={};h.frame=o.frame,h.value=n,l!=null&&(h.inTangent=l),c!=null&&(h.outTangent=c),u!=null&&(h.interpolation=u),r.push(h)}if(t.setKeys(r),e.ranges)for(a=0;a{const n=new On;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){let a=JSON.parse(n.responseText);if(a.animations&&(a=a.animations),a.length){const o=[];for(const l of a)o.push(this.Parse(l));i(o)}else{const o=this.Parse(a);e&&(o.name=e),i(o)}}else r("Unable to load the animation")}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const r=new On;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){const n=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(n.animations){const a=JSON.parse(n.animations),o=[];for(const l of a.animations){const c=this.Parse(l);c.snippetId=e,o.push(c)}t(o)}else{const a=JSON.parse(n.animation),o=this.Parse(a);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};tt._UniqueIdGenerator=0;tt.AllowMatricesInterpolation=!1;tt.AllowMatrixDecomposeForInterpolation=!0;tt.SnippetUrl="https://snippet.babylonjs.com";tt.ANIMATIONTYPE_FLOAT=0;tt.ANIMATIONTYPE_VECTOR3=1;tt.ANIMATIONTYPE_QUATERNION=2;tt.ANIMATIONTYPE_MATRIX=3;tt.ANIMATIONTYPE_COLOR3=4;tt.ANIMATIONTYPE_COLOR4=7;tt.ANIMATIONTYPE_VECTOR2=5;tt.ANIMATIONTYPE_SIZE=6;tt.ANIMATIONLOOPMODE_RELATIVE=0;tt.ANIMATIONLOOPMODE_CYCLE=1;tt.ANIMATIONLOOPMODE_CONSTANT=2;tt.ANIMATIONLOOPMODE_YOYO=4;tt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;tt.CreateFromSnippetAsync=tt.ParseFromSnippetAsync;ve("BABYLON.Animation",tt);ns._AnimationRangeFactory=(s,e,t)=>new $S(s,e,t);class WFe extends an{constructor(e,t,i,r,n=1e3,a,o,l){super(e,a),this.duration=1e3,this.onInterpolationDoneObservable=new Ae,this.propertyPath=i,this.value=r,this.duration=n,this.stopOtherAnimations=o,this.onInterpolationDone=l,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if(typeof this.value=="number")i=tt.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Re)i=tt.ANIMATIONTYPE_COLOR3;else if(this.value instanceof D)i=tt.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof he)i=tt.ANIMATIONTYPE_MATRIX;else if(this.value instanceof Pe)i=tt.ANIMATIONTYPE_QUATERNION;else{fe.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const r=new tt("InterpolateValueAction",this._property,100*(1e3/this.duration),i,tt.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);const n=()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()};e.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,n)}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[an._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:an._SerializeValueAsString(this.value)},{name:"duration",value:an._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:an._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}ve("BABYLON.InterpolateValueAction",WFe);class KFe{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,r){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===tt.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=he.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,this._minFrame!==0){const a={frame:0,value:this._minValue};this._keys.splice(0,0,a)}if(this._target instanceof Array){let a=0;for(const o of this._target)this._preparePath(o,a),this._getOriginalValues(a),a++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const n=t.getEvents();n&&n.length>0&&n.forEach(a=>{this._events.push(a._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let r=e;for(let n=0;n-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const r=this._events;if(r.length)for(let a=0;athis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const u=i-t;let h,d=e*(o.framePerSecond*n)/1e3+this._absoluteFrameOffset,f=0,p=!1;const m=r&&this._animationState.loopMode===tt.ANIMATIONLOOPMODE_YOYO;if(m){const v=(d-t)/u,x=Math.sin(v*Math.PI);d=Math.abs(x)*u+t;const b=x>=0?1:-1;this._yoyoDirection!==b&&(p=!0),this._yoyoDirection=b}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&(d>=u&&n>0||d<=0&&n<0))c=!1,f=o._getKeyValue(this._maxValue);else if(!r&&t>=i&&(d<=u&&n<0||d>=0&&n>0))c=!1,f=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==tt.ANIMATIONLOOPMODE_CYCLE){const v=i.toString()+t.toString();if(!this._offsetsCache[v]){this._animationState.repeatCount=0,this._animationState.loopMode=tt.ANIMATIONLOOPMODE_CYCLE;const x=o._interpolate(t,this._animationState),A=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case tt.ANIMATIONTYPE_FLOAT:this._offsetsCache[v]=A-x;break;case tt.ANIMATIONTYPE_QUATERNION:this._offsetsCache[v]=A.subtract(x);break;case tt.ANIMATIONTYPE_VECTOR3:this._offsetsCache[v]=A.subtract(x);break;case tt.ANIMATIONTYPE_VECTOR2:this._offsetsCache[v]=A.subtract(x);break;case tt.ANIMATIONTYPE_SIZE:this._offsetsCache[v]=A.subtract(x);break;case tt.ANIMATIONTYPE_COLOR3:this._offsetsCache[v]=A.subtract(x);break}this._highLimitsCache[v]=A}f=this._highLimitsCache[v],h=this._offsetsCache[v]}if(h===void 0)switch(o.dataType){case tt.ANIMATIONTYPE_FLOAT:h=0;break;case tt.ANIMATIONTYPE_QUATERNION:h=ege;break;case tt.ANIMATIONTYPE_VECTOR3:h=tge;break;case tt.ANIMATIONTYPE_VECTOR2:h=ige;break;case tt.ANIMATIONTYPE_SIZE:h=rge;break;case tt.ANIMATIONTYPE_COLOR3:h=sge;break;case tt.ANIMATIONTYPE_COLOR4:h=nge;break}let g;if(this._host&&this._host.syncRoot){const v=this._host.syncRoot,x=(v.masterFrame-v.fromFrame)/(v.toFrame-v.fromFrame);g=t+u*x}else d>0&&t>i||d<0&&t0&&this.currentFrame>g||n<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=g,this._animationState.repeatCount=u===0?0:d/u>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=h;const y=o._interpolate(g,this._animationState);if(this.setValue(y,a),_.length){for(let v=0;v<_.length;v++)if(u>=0&&g>=_[v].frame&&_[v].frame>=t||u<0&&g<=_[v].frame&&_[v].frame<=t){const x=_[v];x.isDone||(x.onlyOnce&&(_.splice(v,1),v--),x.isDone=!0,x.action(g))}}return c||(this._stopped=!0),c}}function To(){return typeof window<"u"}function Ny(){return typeof navigator<"u"}function MS(){return typeof document<"u"}function az(s){let e="",t=s.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const r_t={IsWindowObjectExist:To,IsNavigatorAvailable:Ny,IsDocumentAvailable:MS,GetDOMTextContent:az};class Or{static get Now(){return To()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class RS{}RS.FilesToLoad={};class HFe{static ExponentialBackoff(e=3,t=500){return(i,r,n)=>r.status!==0||n>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,n)*t}}class ZS extends Error{}ZS._setPrototypeOf=Object.setPrototypeOf||((s,e)=>(s.__proto__=e,s));const x_={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class R0 extends ZS{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",ZS._setPrototypeOf(this,R0.prototype)}}const jFe=(s,e)=>s.endsWith(e),XFe=(s,e)=>s?s.startsWith(e):!1,age=s=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(s);let e="";for(let t=0;t{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,r,n,a,o,l,c,u=0;const h=ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);for(;u>2,o=(i&3)<<4|r>>4,l=(r&15)<<2|n>>6,c=n&63,isNaN(r)?l=c=64:isNaN(n)&&(c=64),t+=e.charAt(a)+e.charAt(o)+e.charAt(l)+e.charAt(c);return t},AJ=s=>atob(s),lz=s=>{const e=AJ(s),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let r=0;r{let t=String(s);for(;t.length{i+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class o_t{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const n=t.split(";");for(let a=0;a{u=u.trim(),u!==""&&(i.push(u),u="")},a=h=>{rWa._Stack[r],l=()=>r===-1?"!!INVALID EXPRESSION!!":Wa._Stack[r--];let c=0,u="";for(;c1){for(n();r!==-1&&Wa._OperatorPriority[o()]>=Wa._OperatorPriority[d];)i.push(l());a(d),c++}else u+=h;c++}for(n();r!==-1;)o()==="("?l():i.push(l());return Wa._InfixToPostfixCache.size>=Wa.InfixToPostfixCacheLimitSize&&Wa.ClearCache(),Wa._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Wa._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=r>n;break;case"<":i=r=":i=r>=n;break;case"==":i=r===n;break;case"!=":i=r!==n;break}return i}}const sZ={};function QFe(s,e,t=""){return t+(e?e+` `:"")+s}function $Fe(s,e,t,i,r,n,a){const o=a||sZ.loadFile;if(o)return o(s,e,t,i,r,n);throw vi("FileTools")}function ZFe(s,e,t,i){if(s){e?s.IS_NDC_HALF_ZRANGE="":delete s.IS_NDC_HALF_ZRANGE,t?s.USE_REVERSE_DEPTHBUFFER="":delete s.USE_REVERSE_DEPTHBUFFER,i?s.USE_EXACT_SRGB_CONVERSIONS="":delete s.USE_EXACT_SRGB_CONVERSIONS;return}else{let r="";return e&&(r+="#define IS_NDC_HALF_ZRANGE"),t&&(r&&(r+=` `),r+="#define USE_REVERSE_DEPTHBUFFER"),i&&(r&&(r+=` `),r+="#define USE_EXACT_SRGB_CONVERSIONS"),r}}const d_t=/defined\s*?\((.+?)\)/g,Cne=/defined\s*?\[(.+?)\]/g,f_t=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,p_t=/__decl__/,mTe=/light\{X\}.(\w*)/g,gTe=/\{X\}/g,aY=[],m_t=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function oge(s){s.processor&&s.processor.initializeShaders&&s.processor.initializeShaders(s.processingContext)}function nZ(s,e,t,i){var r;(r=e.processor)!=null&&r.preProcessShaderCode&&(s=e.processor.preProcessShaderCode(s,e.isFragment)),Ok(s,e,n=>{e.processCodeAfterIncludes&&(n=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",n,e.defines));const a=y_t(n,e,i);t(a,n)})}function g_t(s,e,t,i){var r;(r=e.processor)!=null&&r.preProcessShaderCode&&(s=e.processor.preProcessShaderCode(s,e.isFragment)),Ok(s,e,n=>{e.processCodeAfterIncludes&&(n=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",n,e.defines));const a=x_t(n,e,i);t(a,n)})}function lge(s,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:s,fragmentCode:e}:t.processor.finalizeShaders(s,e,t.processingContext)}function __t(s,e){var i;if((i=e.processor)!=null&&i.noPrecision)return s;const t=e.shouldUseHighPrecisionShader;return s.indexOf("precision highp float")===-1?t?s=`precision highp float; `+s:s=`precision mediump float; `+s:t||(s=s.replace("precision highp float","precision mediump float")),s}function Sne(s){const t=/defined\((.+)\)/.exec(s);if(t&&t.length)return new rZ(t[1].trim(),s[0]==="!");const i=["==","!=",">=","<=","<",">"];let r="",n=0;for(r of i)if(n=s.indexOf(r),n>-1)break;if(n===-1)return new rZ(s);const a=s.substring(0,n).trim(),o=s.substring(n+r.length).trim();return new h_t(a,r,o)}function v_t(s){s=s.replace(d_t,"defined[$1]");const e=Wa.infixToPostfix(s),t=[];for(const r of e)if(r!=="||"&&r!=="&&")t.push(r);else if(t.length>=2){let n=t[t.length-1],a=t[t.length-2];t.length-=2;const o=r=="&&"?new u_t:new c_t;typeof n=="string"&&(n=n.replace(Cne,"defined($1)")),typeof a=="string"&&(a=a.replace(Cne,"defined($1)")),o.leftOperand=typeof a=="string"?Sne(a):a,o.rightOperand=typeof n=="string"?Sne(n):n,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(Cne,"defined($1)")),typeof i=="string"?Sne(i):i}function jQ(s,e){const t=new l_t,i=s.substring(0,e);let r=s.substring(e);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new rZ(r):i==="#ifndef"?t.testExpression=new rZ(r,!0):t.testExpression=v_t(r),t}function Ene(s,e,t){let i=s.currentLine;for(;due(s,t);){i=s.currentLine;const r=i.substring(0,5).toLowerCase();if(r==="#else"){const n=new cz;e.children.push(n),due(s,n);return}else if(r==="#elif"){const n=jQ(i,5);e.children.push(n),t=n}}}function due(s,e){for(;s.canRead;){s.lineIndex++;const t=s.currentLine;if(t.indexOf("#")>=0){const r=m_t.exec(t);if(r&&r.length){switch(r[0]){case"#ifdef":{const a=new bne;e.children.push(a);const o=jQ(t,6);a.children.push(o),Ene(s,a,o);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const a=new bne;e.children.push(a);const o=jQ(t,7);a.children.push(o),Ene(s,a,o);break}case"#if":{const a=new bne,o=jQ(t,3);e.children.push(a),a.children.push(o),Ene(s,a,o);break}}continue}}const i=new cz;if(i.line=t,e.children.push(i),t[0]==="#"&&t[1]==="d"){const r=t.replace(";","").split(" ");i.additionalDefineKey=r[1],r.length===3&&(i.additionalDefineValue=r[2])}}return!1}function qFe(s,e,t){const i=new cz,r=new o_t;return r.lineIndex=-1,r.lines=s.split(` `),due(r,i),i.process(e,t)}function JFe(s,e){var r;const t=s.defines,i={};for(const n of t){const o=n.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((r=s.processor)==null?void 0:r.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=s.version,i[s.platformName]="true",ZFe(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function y_t(s,e,t){let i=__t(s,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;const r=e.defines,n=JFe(e,t);return e.processor.preProcessor&&(i=e.processor.preProcessor(i,r,n,e.isFragment,e.processingContext)),i=qFe(i,n,e),e.processor.postProcessor&&(i=e.processor.postProcessor(i,r,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function x_t(s,e,t){var a,o;let i=s;const r=e.defines,n=JFe(e,t);return(a=e.processor)!=null&&a.preProcessor&&(i=e.processor.preProcessor(i,r,n,e.isFragment,e.processingContext)),i=qFe(i,n,e),(o=e.processor)!=null&&o.postProcessor&&(i=e.processor.postProcessor(i,r,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Ok(s,e,t){aY.length=0;let i;for(;(i=f_t.exec(s))!==null;)aY.push(i);let r=String(s),n=[s],a=!1;for(const o of aY){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(p_t,""),e.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),e.includesShadersStore[l]){let c=e.includesShadersStore[l];if(o[2]){const h=o[3].split(",");for(let d=0;dy+"{X}")),c+=m.replace(gTe,g.toString())+` `}else e.supportsUniformBuffers||(c=c.replace(mTe,(d,f)=>f+"{X}")),c=c.replace(gTe,h)}const u=[];for(const h of n){const d=h.split(o[0]);for(let f=0;f=0||c.indexOf("#include <")>=0}else{const c=e.shadersRepository+"ShadersInclude/"+l+".fx";e9e.loadFile(c,u=>{e.includesShadersStore[l]=u,Ok(n.join(""),e,t)});return}}aY.length=0,r=n.join(""),a?Ok(r.toString(),e,t):t(r)}const e9e={loadFile:(s,e,t,i,r,n)=>{throw vi("FileTools")}};class ew{static SetImmediate(e){To()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class de{static GetShadersRepository(e=0){return e===0?de.ShadersRepository:de.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?de.ShadersStore:de.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?de.IncludesShadersStore:de.IncludesShadersStoreWGSL}}de.ShadersRepository="src/Shaders/";de.ShadersStore={};de.IncludesShadersStore={};de.ShadersRepositoryWGSL="src/ShadersWGSL/";de.ShadersStoreWGSL={};de.IncludesShadersStoreWGSL={};class t9e{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,r,n,a,o,l){const c=this.engine;if(c.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this.engine.getUniforms(this,i).forEach((d,f)=>{r[i[f]]=d}),this._uniforms=r;let h;for(h=0;h{a[d]=f});for(const d of c.getAttributes(this,o))l.push(d)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||r.length!==2)return r=[t,i],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n}_cacheFloat3(e,t,i,r){let n=this._valueCache[e];if(!n||n.length!==3)return n=[t,i,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,n){let a=this._valueCache[e];if(!a||a.length!==4)return a=[t,i,r,n],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==n&&(a[3]=n,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this.engine.setInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const fue=new WeakMap,A_t={_webGLVersion:2,cachedPipelines:{}};function Ff(s){let e=fue.get(s);if(!e){if(!s)return A_t;e={_webGLVersion:s.TEXTURE_BINDING_3D?2:1,_context:s,cachedPipelines:{}},fue.set(s,e)}return e}function b_t(s){fue.delete(s)}function i9e(s,e,t,i,r,n){const a=Ff(i);n||(n=a._createShaderProgramInjection??cge);const o=pue(e,"vertex",i,a._contextWasLost),l=pue(t,"fragment",i,a._contextWasLost);return n(s,o,l,i,r,a.validateShaderPrograms)}function r9e(s,e,t,i,r,n=null,a){const o=Ff(r);a||(a=o._createShaderProgramInjection??cge);const l=o._webGLVersion>1?`#version 300 es #define WEBGL2 `:"",c=_Te(e,"vertex",i,l,r,o._contextWasLost),u=_Te(t,"fragment",i,l,r,o._contextWasLost);return a(s,c,u,r,n,o.validateShaderPrograms)}function C_t(s,e){const t=new t9e,i=Ff(s);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function cge(s,e,t,i,r=null,n){const a=i.createProgram();if(s.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,e),i.attachShader(a,t),i.linkProgram(a),s.context=i,s.vertexShader=e,s.fragmentShader=t,s.isParallelCompiled||s9e(s,i,n),a}function s9e(s,e,t){const i=s.context,r=s.vertexShader,n=s.fragmentShader,a=s.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!e.getShaderParameter(r,e.COMPILE_STATUS)){const c=e.getShaderInfoLog(r);if(c)throw s.vertexCompilationError=c,new Error("VERTEX SHADER "+c)}if(!e.getShaderParameter(n,e.COMPILE_STATUS)){const c=e.getShaderInfoLog(n);if(c)throw s.fragmentCompilationError=c,new Error("FRAGMENT SHADER "+c)}const l=i.getProgramInfoLog(a);if(l)throw s.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(a),!i.getProgramParameter(a,i.VALIDATE_STATUS))){const c=i.getProgramInfoLog(a);if(c)throw s.programValidationError=c,new Error(c)}i.deleteShader(r),i.deleteShader(n),s.vertexShader=void 0,s.fragmentShader=void 0,s.onCompiled&&(s.onCompiled(),s.onCompiled=void 0)}function S_t(s,e,t,i,r,n,a,o,l,c="",u,h,d){const f=Ff(s.context);h||(h=f.createRawShaderProgramInjection??i9e),d||(d=f.createShaderProgramInjection??r9e);const p=s;i?p.program=h(p,e,t,p.context,l):p.program=d(p,e,t,o,p.context,l),p.program.__SPECTOR_rebuildProgram=a,u()}function _Te(s,e,t,i,r,n){return pue(QFe(s,t,i),e,r,n)}function pue(s,e,t,i){const r=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!r){let n=t.NO_ERROR,a=t.NO_ERROR;for(;(a=t.getError())!==t.NO_ERROR;)n=a;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${n}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(r,s),t.compileShader(r),r}function E_t(s,e){e.useProgram(s)}function T_t(s,e){const t=s;if(!t.isParallelCompiled){e(s);return}const i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(s)}}function M_t(s,e){return Ff(e).cachedPipelines[s]}function uge(s){const e=s._name,t=s.context;if(e&&t){const i=Ff(t),r=i.cachedPipelines[e];r==null||r.dispose(),delete i.cachedPipelines[e]}}function R_t(s,e,t,i,r,n,a){let o,l;const c=To()?n==null?void 0:n.getHostDocument():null;typeof e=="string"?o=e:e.vertexSource?o="source:"+e.vertexSource:e.vertexElement?o=(c==null?void 0:c.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?l=e:e.fragmentSource?l="source:"+e.fragmentSource:e.fragmentElement?l=(c==null?void 0:c.getElementById(e.fragmentElement))||e.fragmentElement:l=e.fragment||e;const u=[void 0,void 0],h=()=>{if(u[0]&&u[1]){s.isFragment=!0;const[d,f]=u;nZ(f,s,(p,m)=>{a&&(a._fragmentSourceCodeBeforeMigration=m),t&&(p=t("fragment",p));const g=lge(d,p,s);s=null;const _=I_t(g.vertexCode,g.fragmentCode,e,r);i==null||i(_.vertexSourceCode,_.fragmentSourceCode)},n)}};vTe(o,"Vertex","",d=>{oge(s),nZ(d,s,(f,p)=>{a&&(a._rawVertexSourceCode=d,a._vertexSourceCodeBeforeMigration=p),t&&(f=t("vertex",f)),u[0]=f,h()},n)},r),vTe(l,"Fragment","Pixel",d=>{a&&(a._rawFragmentSourceCode=d),u[1]=d,h()},r)}function vTe(s,e,t,i,r,n){if(typeof HTMLElement<"u"&&s instanceof HTMLElement){const l=az(s);i(l);return}if(s.substr(0,7)==="source:"){i(s.substr(7));return}if(s.substr(0,7)==="base64:"){const l=window.atob(s.substr(7));i(l);return}const a=de.GetShadersStore(r);if(a[s+e+"Shader"]){i(a[s+e+"Shader"]);return}if(t&&a[s+t+"Shader"]){i(a[s+t+"Shader"]);return}let o;if(s[0]==="."||s[0]==="/"||s.indexOf("http")>-1?o=s:o=de.GetShadersRepository(r)+s,n=n||$Fe,!n)throw new Error("loadFileInjection is not defined");n(o+"."+e.toLowerCase()+".fx",i)}function I_t(s,e,t,i){if(t){const r=t.vertexElement||t.vertex||t.spectorName||t,n=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+r+` `+s,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+n+` `+e}}else return{vertexSourceCode:s,fragmentSourceCode:e}}const P_t=(s,e,t,i)=>{try{const r=s.existingPipelineContext||e(s.shaderProcessingContext);if(r._name=s.name,s.name&&s.context){const n=Ff(s.context);n.cachedPipelines[s.name]=r}return t(r,s.vertex,s.fragment,!!s.createAsRaw,"","",s.rebuildRebind,s.defines,s.transformFeedbackVaryings,"",()=>{i(r,()=>{var n;(n=s.onRenderingStateCompiled)==null||n.call(s,r)})}),r}catch(r){throw fe.Error("Error compiling effect"),r}};class zi{static get ShadersRepository(){return de.ShadersRepository}static set ShadersRepository(e){de.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Ae),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,n,a=null,o=null,l=null,c=null,u,h="",d=0,f){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new Ae,this.onErrorObservable=new Ae,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=h;const p=this._key.replace(/\r/g,"").replace(/\n/g,"|");let m;if(t.attributes){const g=t;if(this._engine=i,this._attributesNames=g.attributes,this._uniformsNames=g.uniformsNames.concat(g.samplers),this._samplerList=g.samplers.slice(),this.defines=g.defines,this.onError=g.onError,this.onCompiled=g.onCompiled,this._fallbacks=g.fallbacks,this._indexParameters=g.indexParameters,this._transformFeedbackVaryings=g.transformFeedbackVaryings||null,this._multiTarget=!!g.multiTarget,this._shaderLanguage=g.shaderLanguage??0,g.uniformBuffersNames){this._uniformBuffersNamesList=g.uniformBuffersNames.slice();for(let _=0;_{this._vertexSourceCode=a,this._fragmentSourceCode=o,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}get vertexSourceCode(){var e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())??this._vertexSourceCode}get fragmentSourceCode(){var e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split(` `),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(n,a)=>{r&&r(a)},this.onCompiled=()=>{var a,o;const n=this.getEngine().scenes;if(n)for(let l=0;lthis._rebuildProgram(l,c,u,h),defines:r,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:l=>{t&&!e&&this._engine._deletePipelineContext(t),l&&this._onRenderingStateCompiled(l)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){const r=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const a=t.match(r);if(a&&a.length===2){const o=parseInt(a[1]),l=e.split(` `,-1);l.length>=o&&(n=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,n]}_processCompilationErrors(e,t=null){var a,o,l;this._compilationError=e.message;const i=this._attributesNames,r=this._fallbacks;if(fe.Error("Unable to compile effect:"),fe.Error("Uniforms: "+this._uniformsNames.map(function(c){return" "+c})),fe.Error("Attributes: "+i.map(function(c){return" "+c})),fe.Error(`Defines: `+this.defines),zi.LogShaderCodeOnCompilationError){let c=null,u=null,h=null;(a=this._pipelineContext)!=null&&a._getVertexShaderCode()&&([h,c]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),h&&(fe.Error("Vertex code:"),fe.Error(h))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([h,u]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),h&&(fe.Error("Fragment code:"),fe.Error(h))),c&&fe.Error(c),u&&fe.Error(u)}fe.Error("Error: "+this._compilationError);const n=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,n()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,fe.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,n(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||n())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const r=this._samplerList.indexOf(e);for(let a=1;a0)&&(this._pipelineContext&&uge(this._pipelineContext),this._engine._releaseEffect(this),this._isDisposed=!0)}static RegisterShader(e,t,i,r=0){t&&(de.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(de.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){zi._BaseCache={}}}zi.LogShaderCodeOnCompilationError=!0;zi._UniqueIdSeed=0;zi._BaseCache={};zi.ShadersStore=de.ShadersStore;zi.IncludesShadersStore=de.IncludesShadersStore;class hge{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class dge{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,(e=this.stencilGlobal)==null||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var i;if(!e)return;const t=!this.useStencilGlobalOnly&&!!((i=this.stencilMaterial)!=null&&i.enabled);this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class K1{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=K1.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=K1.KEEP,this.opDepthFail=K1.KEEP,this.opStencilDepthPass=K1.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}K1.ALWAYS=519;K1.KEEP=7680;K1.REPLACE=7681;class n9e{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}class fge{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,n=2,a=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=n,this._comparisonFunction=a,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var mue;(function(s){s[s.Unknown=0]="Unknown",s[s.Url=1]="Url",s[s.Temp=2]="Temp",s[s.Raw=3]="Raw",s[s.Dynamic=4]="Dynamic",s[s.RenderTarget=5]="RenderTarget",s[s.MultiRenderTarget=6]="MultiRenderTarget",s[s.Cube=7]="Cube",s[s.CubeRaw=8]="CubeRaw",s[s.CubePrefiltered=9]="CubePrefiltered",s[s.Raw3D=10]="Raw3D",s[s.Raw2DArray=11]="Raw2DArray",s[s.DepthStencil=12]="DepthStencil",s[s.CubeRawRGBD=13]="CubeRawRGBD",s[s.Depth=14]="Depth"})(mue||(mue={}));class zr extends fge{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new Ae,this.onErrorObservable=new Ae,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._engine=e,this._source=t,this._uniqueId=zr._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const t=this.onRebuildCallback(this),i=r=>{r._swapAndDie(this,!1),this.isReady=t.isReady};t.isAsync?t.proxy.then(i):i(t.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,t=>{t._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case 3:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,t=>{t&&t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var n;(n=this._hardwareTexture)==null||n.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let r=i.indexOf(this);r!==-1&&i.splice(r,1),r=i.indexOf(e),r===-1&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}zr._Counter=0;const w_t="modulepreload",D_t=function(s){return"/view/"+s},yTe={},Ue=function(e,t,i){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));r=Promise.allSettled(t.map(l=>{if(l=D_t(l),l in yTe)return;yTe[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const h=document.createElement("link");if(h.rel=c?"stylesheet":w_t,c||(h.as="script"),h.crossOrigin="",h.href=l,o&&h.setAttribute("nonce",o),document.head.appendChild(h),c)return new Promise((d,f)=>{h.addEventListener("load",d),h.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}function n(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return r.then(a=>{for(const o of a||[])o.status==="rejected"&&n(o.reason);return e().catch(n)})};function bJ(s,e){return s.endsWith(".dds")?Ue(()=>Promise.resolve().then(()=>$4t),void 0).then(t=>new t._DDSTextureLoader):s.endsWith(".basis")?Ue(()=>Promise.resolve().then(()=>FEt),void 0).then(t=>new t._BasisTextureLoader):s.endsWith(".env")?Ue(()=>Promise.resolve().then(()=>Z4t),void 0).then(t=>new t._ENVTextureLoader):s.endsWith(".hdr")?Ue(()=>Promise.resolve().then(()=>MEt),void 0).then(t=>new t._HDRTextureLoader):s.endsWith(".ktx")||s.endsWith(".ktx2")||e==="image/ktx"||e==="image/ktx2"?Ue(()=>Promise.resolve().then(()=>tyt),void 0).then(t=>new t._KTXTextureLoader):s.endsWith(".tga")?Ue(()=>Promise.resolve().then(()=>TEt),void 0).then(t=>new t._TGATextureLoader):s.endsWith(".exr")?Ue(()=>Promise.resolve().then(()=>aTt),void 0).then(t=>new t._ExrTextureLoader):null}function pge(s,e){if(To()){const{requestAnimationFrame:t}=e||window;if(typeof t=="function")return t(s)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(s);return setTimeout(s,16)}class Ge{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+=` `),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+=` `),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}zi.ResetCache()}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){fe.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=n,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){const e=this._frameHandler;if(this._frameHandler=0,To()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(b).toLowerCase():"");C.indexOf("?")>-1&&(C=C.split("?")[0]);const w=bJ(C,p);r&&r.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=n,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(x._buffer=u);let P=null;a&&!h&&(P=x.onLoadedObservable.add(a)),h||this._internalTexturesCache.push(x);const M=(R,I)=>{r&&r.removePendingData(x),e===A?(P&&x.onLoadedObservable.remove(P),Rt.UseFallbackTexture&&e!==Rt.FallbackTexture&&this._createTextureBase(Rt.FallbackTexture,t,x.invertY,r,n,null,o,l,c,u,x),R=(R||"Unknown error")+(Rt.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:R,exception:I}),o&&o(R,I)):(fe.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,x.invertY,r,n,a,o,l,c,u,x,d,f,p,m,g))};if(w){const R=async I=>{(await w).loadData(I,x,(k,V,H,j,z,K)=>{K?M("TextureLoader failed to load data"):l(x,C,r,{width:k,height:V},x.invertY,!H,j,()=>(z(),!1),n)},m)};u?u instanceof ArrayBuffer?R(new Uint8Array(u)):ArrayBuffer.isView(u)?R(u):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,I=>R(new Uint8Array(I)),void 0,r?r.offlineProvider:void 0,!0,(I,L)=>{M("Unable to load "+(I&&I.responseURL,L))})}else{const R=I=>{y&&!this._doNotHandleContextLost&&(x._buffer=I),l(x,C,r,I,x.invertY,t,!1,c,n)};!_||v?u&&(typeof u.decoding=="string"||u.close)?R(u):Ge._FileToolsLoadImage(e||"",R,M,r?r.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof u=="string"||u instanceof ArrayBuffer||ArrayBuffer.isView(u)||u instanceof Blob?Ge._FileToolsLoadImage(u,R,M,r?r.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):u&&R(u)}return x}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:MS()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.22.0"}static get Version(){return"7.22.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){var a,o;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new hge,this._stencilStateComposer=new dge,this._stencilState=new K1,this._alphaState=new n9e,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new Ae,this.onCanvasFocusObservable=new Ae,this.onNewSceneAddedObservable=new Ae,this.onResizeObservable=new Ae,this.onCanvasPointerOutObservable=new Ae,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new Ae,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new Ae,this.onAfterShaderCompilationObservable=new Ae,this.onBeginFrameObservable=new Ae,this.onEndFrameObservable=new Ae,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new Ae,this.onContextRestoredObservable=new Ae,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new Ae,Rt.Instances.push(this),this.startTime=Or.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,al.SetMatrixPrecision(!!t.useHighPrecisionMatrix),Ny()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=((a=t.audioEngineOptions)==null?void 0:a.audioContext)??null,this._audioDestination=((o=t.audioEngineOptions)==null?void 0:o.audioDestination)??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const r=To()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||r;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,r):1,this._lastDevicePixelRatio=r,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const r=To()&&window.devicePixelRatio||1,n=this._lastDevicePixelRatio/r;this._lastDevicePixelRatio=r,this._hardwareScalingLevel*=n}if(To()&&MS())if(this._renderingCanvas){const r=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||r.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||r.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let r=0;r{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&MS()&&"ontouchend"in document},this._checkForMobile(),To()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){var t;(t=this._drawCalls)==null||t.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if(typeof document>"u")return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return Ge._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,r,n,a){throw vi("FileTools")}_loadFile(e,t,i,r,n,a){const o=$Fe(e,t,i,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(()=>{const l=this._activeRequests.indexOf(o);l!==-1&&this._activeRequests.splice(l,1)}),o}static _FileToolsLoadFile(e,t,i,r,n,a){if(sZ.loadFile)return sZ.loadFile(e,t,i,r,n,a);throw vi("FileTools")}dispose(){var t;for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();(t=this.releaseComputeEffects)==null||t.call(this),zi.ResetCache();for(const i of this._activeRequests)i.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),To()&&window.removeEventListener("resize",this._checkForMobile);const e=Rt.Instances.indexOf(this);e>=0&&Rt.Instances.splice(e,1),Rt.Instances.length||(Rt.OnEnginesDisposedObservable.notifyObservers(this),Rt.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw vi("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i(s=s.replace(/#/gm,"%23"),s),Ia={DefaultRetryStrategy:HFe.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:s=>s,ScriptBaseUrl:"",ScriptPreprocessUrl:s=>s,CleanUrl:L_t},SJ=(s,e)=>{if(!(s&&s.indexOf("data:")===0)&&Ia.CorsBehavior)if(typeof Ia.CorsBehavior=="string"||Ia.CorsBehavior instanceof String)e.crossOrigin=Ia.CorsBehavior;else{const t=Ia.CorsBehavior(s);t&&(e.crossOrigin=t)}},gue={getRequiredSize:null},Xw=(s,e,t,i,r="",n)=>{const a=Rt.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(a!=null&&a._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;s instanceof ArrayBuffer||ArrayBuffer.isView(s)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([s],{type:r})),l=!0):o=`data:${r};base64,`+oz(s):s instanceof Blob?(o=URL.createObjectURL(s),l=!0):(o=Ia.CleanUrl(s),o=Ia.PreprocessUrl(o));const c=A=>{if(t){const b=o||s.toString();t(`Error while trying to load image: ${b.indexOf("http")===0||b.length<=128?b:b.slice(0,128)+"..."}`,A)}};if(a!=null&&a._features.forceBitmapOverHTMLImageElement)return Uv(o,A=>{a.createImageBitmap(new Blob([A],{type:r}),{premultiplyAlpha:"none",...n}).then(b=>{e(b),l&&URL.revokeObjectURL(o)}).catch(b=>{t&&t("Error while trying to load image: "+s,b)})},void 0,i||void 0,!0,(A,b)=>{c(b)}),null;const u=new Image;if(gue.getRequiredSize){const A=gue.getRequiredSize(s);A.width&&(u.width=A.width),A.height&&(u.height=A.height)}SJ(o,u);const h=[],d=()=>{h.forEach(A=>{A.target.addEventListener(A.name,A.handler)})},f=()=>{h.forEach(A=>{A.target.removeEventListener(A.name,A.handler)}),h.length=0},p=()=>{f(),e(u),l&&u.src&&URL.revokeObjectURL(u.src)},m=A=>{f(),c(A),l&&u.src&&URL.revokeObjectURL(u.src)},g=A=>{if(A.blockedURI!==u.src)return;f();const b=new Error(`CSP violation of policy ${A.effectiveDirective} ${A.blockedURI}. Current policy is ${A.originalPolicy}`);Rt.UseFallbackTexture=!1,c(b),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""};h.push({target:u,name:"load",handler:p}),h.push({target:u,name:"error",handler:m}),h.push({target:document,name:"securitypolicyviolation",handler:g}),d();const _=o.substring(0,5)==="blob:",y=o.substring(0,5)==="data:",v=()=>{_||y||!On.IsCustomRequestAvailable?u.src=o:Uv(o,(A,b,C)=>{const T=!r&&C?C:r,w=new Blob([A],{type:T}),P=URL.createObjectURL(w);l=!0,u.src=P},void 0,i||void 0,!0,(A,b)=>{c(b)})},x=()=>{i&&i.loadImage(o,u)};if(!_&&!y&&i&&i.enableTexturesOffline)i.open(x,v);else{if(o.indexOf("file:")!==-1){const A=decodeURIComponent(o.substring(5).toLowerCase());if(RS.FilesToLoad[A]&&typeof URL<"u"){try{let b;try{b=URL.createObjectURL(RS.FilesToLoad[A])}catch{b=URL.createObjectURL(RS.FilesToLoad[A])}u.src=b,l=!0}catch{u.src=""}return u}}v()}return u},iw=(s,e,t,i,r)=>{const n=new FileReader,a={onCompleteObservable:new Ae,abort:()=>n.abort()};return n.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(n.onerror=()=>{r(new CJ(`Unable to read ${s.name}`,s))}),n.onload=o=>{e(o.target.result)},t&&(n.onprogress=t),i?n.readAsArrayBuffer(s):n.readAsText(s),a},Uv=(s,e,t,i,r,n,a)=>{if(s.name)return iw(s,e,t,r,n?u=>{n(void 0,u)}:void 0);const o=s;if(o.indexOf("file:")!==-1){let u=decodeURIComponent(o.substring(5).toLowerCase());u.indexOf("./")===0&&(u=u.substring(2));const h=RS.FilesToLoad[u];if(h)return iw(h,e,t,r,n?d=>n(void 0,new tw(d.message,d.file)):void 0)}const{match:l,type:c}=o9e(o);if(l){const u={onCompleteObservable:new Ae,abort:()=>()=>{}};try{const h=r?Yw(o):gge(o);e(h,void 0,c)}catch(h){n?n(void 0,h):fe.Error(h.message||"Failed to parse the Data URL")}return ew.SetImmediate(()=>{u.onCompleteObservable.notifyObservers(u)}),u}return EJ(o,(u,h)=>{e(u,h==null?void 0:h.responseURL,h==null?void 0:h.getResponseHeader("content-type"))},t,i,r,n?u=>{n(u.request,new tw(u.message,u.request))}:void 0,a)},EJ=(s,e,t,i,r,n,a)=>{s=Ia.CleanUrl(s),s=Ia.PreprocessUrl(s);const o=Ia.BaseUrl+s;let l=!1;const c={onCompleteObservable:new Ae,abort:()=>l=!0},u=()=>{let h=new On,d=null,f;const p=()=>{h&&(t&&h.removeEventListener("progress",t),f&&h.removeEventListener("readystatechange",f),h.removeEventListener("loadend",m))};let m=()=>{p(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),t=void 0,f=null,m=null,n=void 0,a=void 0,e=void 0};c.abort=()=>{l=!0,m&&m(),h&&h.readyState!==(XMLHttpRequest.DONE||4)&&h.abort(),d!==null&&(clearTimeout(d),d=null),h=null};const g=y=>{const v=y.message||"Unknown error";n&&h?n(new Nk(v,h)):fe.Error(v)},_=y=>{if(h){if(h.open("GET",o),a)try{a(h)}catch(v){g(v);return}r&&(h.responseType="arraybuffer"),t&&h.addEventListener("progress",t),m&&h.addEventListener("loadend",m),f=()=>{if(!(l||!h)&&h.readyState===(XMLHttpRequest.DONE||4)){if(f&&h.removeEventListener("readystatechange",f),h.status>=200&&h.status<300||h.status===0&&(!To()||mge())){try{e&&e(r?h.response:h.responseText,h)}catch(A){g(A)}return}const v=Ia.DefaultRetryStrategy;if(v){const A=v(o,h,y);if(A!==-1){p(),h=new On,d=setTimeout(()=>_(y+1),A);return}}const x=new Nk("Error status: "+h.status+" "+h.statusText+" - Unable to load "+o,h);n&&n(x)}},h.addEventListener("readystatechange",f),h.send()}};_(0)};if(i&&i.enableSceneOffline){const h=f=>{f&&f.status>400?n&&n(f):u()},d=()=>{i&&i.loadFile(Ia.BaseUrl+s,f=>{!l&&e&&e(f),c.onCompleteObservable.notifyObservers(c)},t?f=>{!l&&t&&t(f)}:void 0,h,r)};i.open(d,h)}else u();return c},mge=()=>typeof location<"u"&&location.protocol==="file:",uz=s=>a9e.test(s),o9e=s=>{const e=a9e.exec(s);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function Yw(s){return lz(s.split(",")[1])}const gge=s=>AJ(s.split(",")[1]),O_t=()=>{Ge._FileToolsLoadImage=Xw,sZ.loadFile=Uv,e9e.loadFile=Uv};O_t();let y5;const l9e=(s,e,t,i,r,n,a,o,l,c)=>{y5={DecodeBase64UrlToBinary:s,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:n,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(y5,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(u){t.DefaultRetryStrategy=u}}),Object.defineProperty(y5,"BaseUrl",{get:function(){return t.BaseUrl},set:function(u){t.BaseUrl=u}}),Object.defineProperty(y5,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(u){t.PreprocessUrl=u}}),Object.defineProperty(y5,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(u){t.CorsBehavior=u}})};l9e(Yw,gge,Ia,uz,mge,Uv,Xw,iw,EJ,SJ);class VB{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Xn(e);if(t)return t;fe.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let r=window||this;for(let n=0,a=i.length;n{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}const N_t={RandomId:gh};function Fk(s){let e=1;do e*=2;while(es-t?t:e}function u9e(s){return s--,s|=s>>1,s|=s>>2,s|=s>>4,s|=s>>8,s|=s>>16,s++,s}function _ge(s){return s=s|s>>1,s=s|s>>2,s=s|s>>4,s=s|s>>8,s=s|s>>16,s-(s>>1)}function ad(s,e,t=2){let i;switch(t){case 1:i=_ge(s);break;case 2:i=c9e(s);break;case 3:default:i=u9e(s);break}return Math.min(i,e)}class Me{static get BaseUrl(){return Ia.BaseUrl}static set BaseUrl(e){Ia.BaseUrl=e}static get CleanUrl(){return Ia.CleanUrl}static set CleanUrl(e){Ia.CleanUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://"){Uv(e,n=>{i(n)},void 0,void 0,t,(n,a)=>{r(a)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(Me.ScriptBaseUrl&&e.startsWith(Me._DefaultCdnUrl)){const i=Me.ScriptBaseUrl[Me.ScriptBaseUrl.length-1]==="/"?Me.ScriptBaseUrl.substring(0,Me.ScriptBaseUrl.length-1):Me.ScriptBaseUrl;e=e.replace(Me._DefaultCdnUrl,i)}return e=Me.ScriptPreprocessUrl(e),t&&(e=Me.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=Me.GetBabylonScriptURL(e),Me.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Me.GetBabylonScriptURL(e),Me.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i(`Unable to load script '${e}' in worker`,o)}return}else if(!To()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const n=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=o=>{i&&i(`Unable to load script '${e}'`,o)},n.appendChild(a)}static LoadScriptAsync(e,t){return new Promise((i,r)=>{this.LoadScript(e,()=>{i()},(n,a)=>{r(a||new Error(n))},t)})}static ReadFileAsDataURL(e,t,i){const r=new FileReader,n={onCompleteObservable:new Ae,abort:()=>r.abort()};return r.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},r.onload=a=>{t(a.target.result)},r.onprogress=i,r.readAsDataURL(e),n}static ReadFile(e,t,i,r,n){return iw(e,t,i,r,n)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){Nl.DeepCopy(e,t,i,r)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const l=atob(this.toDataURL(a,o).split(",")[1]),c=l.length,u=new Uint8Array(c);for(let h=0;ht(n)):e.toBlob(function(n){t(n)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}Me.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),r=window.open("");if(!r)return;const n=r.document.createElement("img");n.onload=function(){URL.revokeObjectURL(i)},n.src=i,r.document.body.appendChild(n)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,n){if(typeof r=="string"||!t)this.ToBlob(e,function(a){a&&Me.DownloadBlob(a,r),t&&t("")},i,n);else if(t){if(Me._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:n}).then(o=>{const l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{const c=l.result;t(c)}});return}const a=e.toDataURL(i,n);t(a)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,r,n="image/png",a=!1,o){throw vi("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",n){throw vi("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,n="image/png",a=1,o=!1,l,c=!1,u=!1,h=!0,d){throw vi("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",n=1,a=!1,o,l=!1,c=!1,u=!0,h){throw vi("ScreenshotTools")}static RandomId(){return gh()}static IsBase64(e){return uz(e)}static DecodeBase64(e){return Yw(e)}static get errorsCount(){return fe.errorsCount}static Log(e){fe.Log(e)}static Warn(e){fe.Warn(e)}static Error(e){fe.Error(e)}static get LogCache(){return fe.LogCache}static ClearLogCache(){fe.ClearLogCache()}static set LogLevels(e){fe.LogLevels=e}static set PerformanceLogLevel(e){if((e&Me.PerformanceUserMarkLogLevel)===Me.PerformanceUserMarkLogLevel){Me.StartPerformanceCounter=Me._StartUserMark,Me.EndPerformanceCounter=Me._EndUserMark;return}if((e&Me.PerformanceConsoleLogLevel)===Me.PerformanceConsoleLogLevel){Me.StartPerformanceCounter=Me._StartPerformanceConsole,Me.EndPerformanceCounter=Me._EndPerformanceConsole;return}Me.StartPerformanceCounter=Me._StartPerformanceCounterDisabled,Me.EndPerformanceCounter=Me._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Me._Performance){if(!To())return;Me._Performance=window.performance}!t||!Me._Performance.mark||Me._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!Me._Performance.mark||(Me._Performance.mark(e+"-End"),Me._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Me._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Me._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return Or.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,r=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(r!=null?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return Ny()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}Me.UseCustomRequestHeaders=!1;Me.CustomRequestHeaders=On.CustomRequestHeaders;Me.GetDOMTextContent=az;Me._DefaultCdnUrl="https://cdn.babylonjs.com";Me.GetAbsoluteUrl=typeof document=="object"?s=>{const e=document.createElement("a");return e.href=s,e.href}:typeof URL=="function"&&typeof location=="object"?s=>new URL(s,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};Me.NoneLogLevel=fe.NoneLogLevel;Me.MessageLogLevel=fe.MessageLogLevel;Me.WarningLogLevel=fe.WarningLogLevel;Me.ErrorLogLevel=fe.ErrorLogLevel;Me.AllLogLevel=fe.AllLogLevel;Me.IsWindowObjectExist=To;Me.PerformanceNoneLogLevel=0;Me.PerformanceUserMarkLogLevel=1;Me.PerformanceConsoleLogLevel=2;Me.StartPerformanceCounter=Me._StartPerformanceCounterDisabled;Me.EndPerformanceCounter=Me._EndPerformanceCounterDisabled;function F_t(s,e){return t=>{t.__bjsclassName__=s,t.__bjsmoduleName__=e??null}}class Of{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{n&&n()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(c),n&&n()){o.breakLoop();break}}o.executeNext()},a)},r)}}Me.Mix=_ue;Me.IsExponentOfTwo=Fk;Rt.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class no{constructor(e){this.length=0,this.data=new Array(e),this._id=no._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}no._GlobalId=0;class q2 extends no{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;tthis.add(t,i))}get(e){const t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){const i=this._data[t];e(t,i)}}first(e){for(const t in this._data){const i=this._data[t],r=e(t,i);if(r)return r}return null}}function h9e(s){s.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class Ln{constructor(){this._dirty=!0,this._tempColor=new Ze(0,0,0,0),this._globalCurve=new Ze(0,0,0,0),this._highlightsCurve=new Ze(0,0,0,0),this._midtonesCurve=new Ze(0,0,0,0),this._shadowsCurve=new Ze(0,0,0,0),this._positiveCurve=new Ze(0,0,0,0),this._negativeCurve=new Ze(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",n="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,n){e!=null&&(e=Ln._Clamp(e,0,360),t=Ln._Clamp(t,-100,100),i=Ln._Clamp(i,-100,100),r=Ln._Clamp(r,-100,100),t=Ln._ApplyColorGradingSliderNonlinear(t),t*=.5,r=Ln._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),Ln._FromHSBToRef(e,t,50+.25*r,n),n.scaleToRef(2,n),n.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let n=Ln._Clamp(e,0,360);const a=Ln._Clamp(t/100,0,1),o=Ln._Clamp(i/100,0,1);if(a===0)r.r=o,r.g=o,r.b=o;else{n/=60;const l=Math.floor(n),c=n-l,u=o*(1-a),h=o*(1-a*c),d=o*(1-a*(1-c));switch(l){case 0:r.r=o,r.g=d,r.b=u;break;case 1:r.r=h,r.g=o,r.b=u;break;case 2:r.r=u,r.g=o,r.b=d;break;case 3:r.r=u,r.g=h,r.b=o;break;case 4:r.r=d,r.g=u,r.b=o;break;default:r.r=o,r.g=u,r.b=h;break}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return qe.Clone(()=>new Ln,this)}serialize(){return qe.Serialize(this)}static Parse(e){return qe.Parse(()=>new Ln,e,null,null)}}Ln.PrepareUniforms=h9e;F([X()],Ln.prototype,"_globalHue",void 0);F([X()],Ln.prototype,"_globalDensity",void 0);F([X()],Ln.prototype,"_globalSaturation",void 0);F([X()],Ln.prototype,"_globalExposure",void 0);F([X()],Ln.prototype,"_highlightsHue",void 0);F([X()],Ln.prototype,"_highlightsDensity",void 0);F([X()],Ln.prototype,"_highlightsSaturation",void 0);F([X()],Ln.prototype,"_highlightsExposure",void 0);F([X()],Ln.prototype,"_midtonesHue",void 0);F([X()],Ln.prototype,"_midtonesDensity",void 0);F([X()],Ln.prototype,"_midtonesSaturation",void 0);F([X()],Ln.prototype,"_midtonesExposure",void 0);qe._ColorCurvesParser=Ln.Parse;function d9e(s,e){e.EXPOSURE&&s.push("exposureLinear"),e.CONTRAST&&s.push("contrast"),e.COLORGRADING&&s.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&s.push("vInverseScreenSize"),e.VIGNETTE&&(s.push("vignetteSettings1"),s.push("vignetteSettings2")),e.COLORCURVES&&h9e(s),e.DITHER&&s.push("ditherIntensity")}function f9e(s,e){e.COLORGRADING&&s.push("txColorTransform")}class lr{constructor(){this.colorCurves=new Ln,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=lr.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ze(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=lr.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Ae}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===lr._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case lr.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case lr.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&Ln.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const n=t??r/i;let a=Math.tan(this.vignetteCameraFov*.5),o=a*n;const l=Math.sqrt(o*a);o=_ue(o,l,this.vignetteStretch),a=_ue(a,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,a,-o*this.vignetteCenterX,-a*this.vignetteCenterY);const c=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,c)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return qe.Clone(()=>new lr,this)}serialize(){return qe.Serialize(this)}static Parse(e){const t=qe.Parse(()=>new lr,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}lr.TONEMAPPING_STANDARD=0;lr.TONEMAPPING_ACES=1;lr.TONEMAPPING_KHR_PBR_NEUTRAL=2;lr.PrepareUniforms=d9e;lr.PrepareSamplers=f9e;lr._VIGNETTEMODE_MULTIPLY=0;lr._VIGNETTEMODE_OPAQUE=1;F([zFe()],lr.prototype,"colorCurves",void 0);F([X()],lr.prototype,"_colorCurvesEnabled",void 0);F([ii("colorGradingTexture")],lr.prototype,"_colorGradingTexture",void 0);F([X()],lr.prototype,"_colorGradingEnabled",void 0);F([X()],lr.prototype,"_colorGradingWithGreenDepth",void 0);F([X()],lr.prototype,"_colorGradingBGR",void 0);F([X()],lr.prototype,"_exposure",void 0);F([X()],lr.prototype,"_toneMappingEnabled",void 0);F([X()],lr.prototype,"_toneMappingType",void 0);F([X()],lr.prototype,"_contrast",void 0);F([X()],lr.prototype,"vignetteStretch",void 0);F([X()],lr.prototype,"vignetteCenterX",void 0);F([X()],lr.prototype,"vignetteCenterY",void 0);F([X()],lr.prototype,"vignetteWeight",void 0);F([jw()],lr.prototype,"vignetteColor",void 0);F([X()],lr.prototype,"vignetteCameraFov",void 0);F([X()],lr.prototype,"_vignetteBlendMode",void 0);F([X()],lr.prototype,"_vignetteEnabled",void 0);F([X()],lr.prototype,"_ditheringEnabled",void 0);F([X()],lr.prototype,"_ditheringIntensity",void 0);F([X()],lr.prototype,"_skipFinalColorClamp",void 0);F([X()],lr.prototype,"_applyByPostProcess",void 0);F([X()],lr.prototype,"_isEnabled",void 0);qe._ImageProcessingConfigurationParser=lr.Parse;ve("BABYLON.ImageProcessingConfiguration",lr);function TJ(s){return s.getPipelineContext===void 0}class B_t{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,r,n){if(n.drawBuffersExtensionDisabled){const a=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(a,"")}return e}}const k_t=/(flat\s)?\s*varying\s*.*/;class p9e{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return k_t.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const r=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,n=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(n,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const a=e.search(/layout *\(location *= *0\) *out/g)!==-1;e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(r||a?"":`layout(location = 0) out vec4 glFragColor; `)+"void main(")}else if(t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require layout (num_views = 2) in; `+e;return e}}class Zm{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Zm._Counter++}}Zm._Counter=0;class rw extends Zm{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class tT{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t;return((t=this._MSAARenderBuffers)==null?void 0:t[e])??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class U_t{}class bi extends Ge{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return zi.ShadersRepository}static set ShadersRepository(e){zi.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,r){if(i=i||{},super(t??i.antialias,i,r),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let n=null;if(e.getContext){if(n=e,this._renderingCanvas=n,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const l=navigator.userAgent;for(const c of bi.ExceptionList){const u=c.key,h=c.targets;if(new RegExp(u).test(l)){if(c.capture&&c.captureConstraint){const f=c.capture,p=c.captureConstraint,g=new RegExp(f).exec(l);if(g&&g.length>0&&parseInt(g[g.length-1])>=p)continue}for(const f of h)switch(f){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost||(this._onContextLost=l=>{l.preventDefault(),this._contextWasLost=!0,fe.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},n.addEventListener("webglcontextlost",this._onContextLost,!1),n.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=n.getContext("webgl2",i)||n.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch{}if(!this._gl){if(!n)throw new Error("The provided canvas is null or undefined.");try{this._gl=n.getContext("webgl",i)||n.getContext("experimental-webgl",i)}catch{throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const l=this._gl.getContextAttributes();l&&(i.stencil=l.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let l=0;l1?new p9e:new B_t;const a=`Babylon.js v${bi.Version}`;fe.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a);const o=Ff(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const t=this._gl.getExtension("WEBGL_draw_buffers");if(t!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const t=this._gl.getExtension("WEBGL_depth_texture");t!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=t.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const t=this._gl.getExtension("OES_vertex_array_object");t!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=t.createVertexArrayOES.bind(t),this._gl.bindVertexArray=t.bindVertexArrayOES.bind(t),this._gl.deleteVertexArray=t.deleteVertexArrayOES.bind(t))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const t=this._gl.getExtension("ANGLE_instanced_arrays");t!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=t.drawArraysInstancedANGLE.bind(t),this._gl.drawElementsInstanced=t.drawElementsInstancedANGLE.bind(t),this._gl.vertexAttribDivisor=t.vertexAttribDivisorANGLE.bind(t)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const t=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),i=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);t&&i&&(this._caps.highPrecisionShaderSupported=t.precision!==0&&i.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const t=this._gl.getExtension("EXT_blend_minmax");t!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=t.MAX_EXT,this._gl.MIN=t.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const t=this._gl.getExtension("EXT_sRGB");t!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:t.SRGB_EXT,SRGB8:t.SRGB_ALPHA_EXT,SRGB8_ALPHA8:t.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let t=0;t"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,i,r=!1){var o,l;const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let a=0;if(t&&e){let c=!0;if(this._currentRenderTarget){const u=(o=this._currentRenderTarget.texture)==null?void 0:o.format;if(u===8||u===9||u===10||u===11){const h=(l=this._currentRenderTarget.texture)==null?void 0:l.type;h===7||h===5?(bi._TempClearColorUint32[0]=e.r*255,bi._TempClearColorUint32[1]=e.g*255,bi._TempClearColorUint32[2]=e.b*255,bi._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,bi._TempClearColorUint32),c=!1):(bi._TempClearColorInt32[0]=e.r*255,bi._TempClearColorInt32[1]=e.g*255,bi._TempClearColorInt32[2]=e.b*255,bi._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,bi._TempClearColorInt32),c=!1)}}c&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),a|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),a|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),a|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(a)}_viewport(e,t,i,r){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||r!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,r,n,a=0,o=0){var h,d,f,p,m,g;const l=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(l._MSAAFramebuffer?l._MSAAFramebuffer:l._framebuffer);const c=this._gl;e.isMulti||(e.is2DArray||e.is3D?c.framebufferTextureLayer(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,(h=e.texture._hardwareTexture)==null?void 0:h.underlyingResource,a,o):e.isCube?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+t,(d=e.texture._hardwareTexture)==null?void 0:d.underlyingResource,a):l._currentLOD!==a&&(c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,(f=e.texture._hardwareTexture)==null?void 0:f.underlyingResource,a),l._currentLOD=a));const u=e._depthStencilTexture;if(u){e.is3D&&(e.texture.width!==u.width||e.texture.height!==u.height||e.texture.depth!==u.depth)&&fe.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");const _=e._depthStencilTextureWithStencil?c.DEPTH_STENCIL_ATTACHMENT:c.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?c.framebufferTextureLayer(c.FRAMEBUFFER,_,(p=u._hardwareTexture)==null?void 0:p.underlyingResource,a,o):e.isCube?c.framebufferTexture2D(c.FRAMEBUFFER,_,c.TEXTURE_CUBE_MAP_POSITIVE_X+t,(m=u._hardwareTexture)==null?void 0:m.underlyingResource,a):c.framebufferTexture2D(c.FRAMEBUFFER,_,c.TEXTURE_2D,(g=u._hardwareTexture)==null?void 0:g.underlyingResource,a)}this._cachedViewport&&!n?this.setViewport(this._cachedViewport,i,r):(i||(i=e.width,a&&(i=i/Math.pow(2,a))),r||(r=e.height,a&&(r=r/Math.pow(2,a))),this._viewport(0,0,i,r)),this.wipeCaches()}setState(e,t=0,i,r=!1,n,a,o=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const l=this.cullBackFaces??n??!0?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==l||i)&&(this._depthCullingState.cullFace=l),this.setZOffset(t),this.setZOffsetUnits(o);const c=r?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=a}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t=!1,i){var a;const r=e;this._currentRenderTarget=null;const n=this._gl;if(r._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}n.bindFramebuffer(n.READ_FRAMEBUFFER,r._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,r._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)}(a=e.texture)!=null&&a.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(r._MSAAFramebuffer&&this._bindUnboundFramebuffer(r._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const r=new rw(i);return this.bindArrayBuffer(r),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),r.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),r.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),r.capacity=e),this._resetVertexBufferBinding(),r.references=1,r}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const r=this._gl.createBuffer(),n=new rw(r);if(!r)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const a=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,a,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=a.BYTES_PER_ELEMENT===4,n}_normalizeIndexData(e){if(e.BYTES_PER_ELEMENT===2)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let i=0;i=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const r=e.program,n=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,n,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,n,a,o){const l=this._currentBufferPointers[t];if(!l)return;let c=!1;l.active?(l.buffer!==e&&(l.buffer=e,c=!0),l.size!==i&&(l.size=i,c=!0),l.type!==r&&(l.type=r,c=!0),l.normalized!==n&&(l.normalized=n,c=!0),l.stride!==a&&(l.stride=a,c=!0),l.offset!==o&&(l.offset=o,c=!0)):(c=!0,l.active=!0,l.index=t,l.size=i,l.type=r,l.normalized=n,l.stride=a,l.offset=o,l.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,o):this._gl.vertexAttribPointer(t,i,r,n,a,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let n=0;n=0){const o=r[n];let l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);const c=l.getBuffer();c&&(this._vertexAttribPointer(c,a,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(c))))}}}recordVertexArrayObject(e,t,i,r){const n=this._gl.createVertexArray();if(!n)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;const a=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[l],this._gl.FLOAT,!1,r,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,fe.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,f=new zr(this,r),p=e.width||e,m=e.height||e,g=e.depth||0,_=e.layers||0,y=this._getSamplingParameters(o,n),v=_!==0?d.TEXTURE_2D_ARRAY:g!==0?d.TEXTURE_3D:d.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(a,l,c),A=this._getInternalFormat(l),b=this._getWebGLTextureType(a);return this._bindTextureDirectly(v,f),_!==0?(f.is2DArray=!0,d.texImage3D(v,0,x,p,m,_,0,A,b,null)):g!==0?(f.is3D=!0,d.texImage3D(v,0,x,p,m,g,0,A,b,null)):d.texImage2D(v,0,x,p,m,0,A,b,null),d.texParameteri(v,d.TEXTURE_MAG_FILTER,y.mag),d.texParameteri(v,d.TEXTURE_MIN_FILTER,y.min),d.texParameteri(v,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(v,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),f._useSRGBBuffer=c,f.baseWidth=p,f.baseHeight=m,f.width=p,f.height=m,f.depth=_,f.isReady=!0,f.samples=u,f.generateMipMaps=n,f.samplingMode=o,f.type=a,f.format=l,f.label=h,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,r,n=3,a=null,o=null,l=null,c=null,u=null,h=null,d,f,p,m){return this._createTextureBase(e,t,i,r,n,a,o,(...g)=>this._prepareWebGLTexture(...g,u),(g,_,y,v,x,A)=>{const b=this._gl,C=y.width===g&&y.height===_;x._creationFlags=p??0;const T=this._getTexImageParametersForCreateTexture(x.format,x._useSRGBBuffer);if(C)return b.texImage2D(b.TEXTURE_2D,0,T.internalFormat,T.format,T.type,y),!1;const w=this._caps.maxTextureSize;if(y.width>w||y.height>w||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=g,this._workingCanvas.height=_,this._workingContext.drawImage(y,0,0,y.width,y.height,0,0,g,_),b.texImage2D(b.TEXTURE_2D,0,T.internalFormat,T.format,T.type,this._workingCanvas),x.width=g,x.height=_),!1;{const P=new zr(this,2);this._bindTextureDirectly(b.TEXTURE_2D,P,!0),b.texImage2D(b.TEXTURE_2D,0,T.internalFormat,T.format,T.type,y),this._rescaleTexture(P,x,r,T.format,()=>{this._releaseTexture(P),this._bindTextureDirectly(b.TEXTURE_2D,x,!0),A()})}return!0},l,c,u,h,d,f,m)}_getTexImageParametersForCreateTexture(e,t){let i,r;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),r=i):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,r,n){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const r=this._getTextureTarget(t),n=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,n.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,n.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){const n=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(n,null)}_uploadCompressedDataToTextureDirectly(e,t,i,r,n,a=0,o=0){const l=this._gl;let c=l.TEXTURE_2D;if(e.isCube&&(c=l.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(c,o,t,i,r,0,n)}_uploadDataToTextureDirectly(e,t,i=0,r=0,n,a=!1){const o=this._gl,l=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),u=n===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(n,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let h=o.TEXTURE_2D;e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),f=Math.round(Math.log(e.height)*Math.LOG2E),p=a?e.width:Math.pow(2,Math.max(d-r,0)),m=a?e.height:Math.pow(2,Math.max(f-r,0));o.texImage2D(h,r,u,p,m,0,c,l,t)}updateTextureData(e,t,i,r,n,a,o=0,l=0,c=!1){const u=this._gl,h=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let f=u.TEXTURE_2D,p=u.TEXTURE_2D;e.isCube&&(p=u.TEXTURE_CUBE_MAP_POSITIVE_X+o,f=u.TEXTURE_CUBE_MAP),this._bindTextureDirectly(f,e,!0),u.texSubImage2D(p,l,i,r,n,a,d,h,t),c&&this._gl.generateMipmap(p),this._bindTextureDirectly(f,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){const n=this._gl,a=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,n){const a=this._gl;if(!a)return;const o=this._getSamplingParameters(n,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,o.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,o.min),!i&&!r&&a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,n,a,o,l,c,u){const h=this.getCaps().maxTextureSize,d=Math.min(h,this.needPOTTextures?ad(r.width,h):r.width),f=Math.min(h,this.needPOTTextures?ad(r.height,h):r.height),p=this._gl;if(p){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(n===void 0?!0:!!n),e.baseWidth=r.width,e.baseHeight=r.height,e.width=d,e.height=f,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:u??(t===".jpg"&&!e._useSRGBBuffer?4:5),!l(d,f,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,o,c)})&&this._prepareWebGLTextureContinuation(e,i,a,o,c)}}_setupFramebufferDepthAttachments(e,t,i,r,n=1){const a=this._gl;if(e&&t)return this._createRenderBuffer(i,r,n,a.DEPTH_STENCIL,a.DEPTH24_STENCIL8,a.DEPTH_STENCIL_ATTACHMENT);if(t){let o=a.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=a.DEPTH_COMPONENT32F),this._createRenderBuffer(i,r,n,o,o,a.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,r,n,a.STENCIL_INDEX8,a.STENCIL_INDEX8,a.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,n,a,o=!0){const c=this._gl.createRenderbuffer();return this._updateRenderBuffer(c,e,t,i,r,n,a,o)}_updateRenderBuffer(e,t,i,r,n,a,o,l=!0){const c=this._gl;return c.bindRenderbuffer(c.RENDERBUFFER,e),r>1&&c.renderbufferStorageMultisample?c.renderbufferStorageMultisample(c.RENDERBUFFER,r,a,t,i):c.renderbufferStorage(c.RENDERBUFFER,n,t,i),c.framebufferRenderbuffer(c.FRAMEBUFFER,o,c.RENDERBUFFER,e),l&&c.bindRenderbuffer(c.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e==null||e.release()}_setProgram(e){this._currentProgram!==e&&(E_t(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let r=0;r-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw fe.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,((l=t==null?void 0:t._hardwareTexture)==null?void 0:l.underlyingResource)??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,n=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const c=t.getInternalTexture();c&&(c._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,!i&&a&&(a._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),o=!1),this._activeChannel=e;const l=this._getTextureTarget(a);if(o&&this._bindTextureDirectly(l,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;const c=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=c,t.wrapV=c}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(l,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let n=0;n=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){const e=Object.keys(this._compiledEffects);for(const t of e)this._compiledEffects[t].dispose();this._compiledEffects={}}dispose(){var e;To()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&((e=this._gl.getExtension("WEBGL_lose_context"))==null||e.loseContext()),b_t(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);const a=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&a===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const o=t.RGBA,l=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,r,n=!0,a=!0){const o=n?4:3,l=n?this._gl.RGBA:this._gl.RGB,c=new Uint8Array(r*i*o);return a&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,l,this._gl.UNSIGNED_BYTE,c),Promise.resolve(c)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{const e=Ge._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=t!=null&&!!window.WebGLRenderingContext}catch{this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(this._HasMajorPerformanceCaveat===null)try{const e=Ge._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch{this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}bi._TempClearColorUint32=new Uint32Array(4);bi._TempClearColorInt32=new Int32Array(4);bi.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];bi._ConcatenateShader=QFe;bi._IsSupported=null;bi._HasMajorPerformanceCaveat=null;bi.prototype.createUniformBuffer=function(s,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new rw(t);return this.bindUniformBuffer(i),s instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,s,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(s),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};bi.prototype.createDynamicUniformBuffer=function(s,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new rw(t);return this.bindUniformBuffer(i),s instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,s,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(s),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};bi.prototype.updateUniformBuffer=function(s,e,t,i){this.bindUniformBuffer(s),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};bi.prototype.bindUniformBuffer=function(s){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,s?s.underlyingResource:null)};bi.prototype.bindUniformBufferBase=function(s,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,s?s.underlyingResource:null)};bi.prototype.bindUniformBlock=function(s,e,t){const i=s.program,r=this._gl.getUniformBlockIndex(i,e);r!==4294967295&&this._gl.uniformBlockBinding(i,r,t)};class zt{constructor(e,t,i,r,n=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||n,this._dynamic=i,this._name=r??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic!==void 0}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){const i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const r=this._uniformLocationPointer-i;for(let n=0;n0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},t==16)t=t*i;else{const a=(4-t)*i;t=t*i+a}r=[];for(let n=0;n1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(zt._UpdatedUbosInFrame[this._name]||(zt._UpdatedUbosInFrame[this._name]=0),zt._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(r===void 0){if(this._buffer){fe.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let n=0;n0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}fe.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}};class ${get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,n,a,o,l,c,u,h=!1,d=!1,f=1,p=!1){this._isDisposed=!1;let m=!1;if(this.engine=e,typeof r=="object"&&r!==null?(m=r.updatable??!1,n=r.postponeInternalCreation,a=r.stride,o=r.instanced,l=r.offset,c=r.size,u=r.type,h=r.normalized??!1,d=r.useBytes??!1,f=r.divisor??1,p=r.takeBufferOwnership??!1,this._label=r.label):m=!!r,t instanceof Mo?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new Mo(e,t,m,a,n,o,d,f,this._label),this._ownsBuffer=!0),this.uniqueId=$._Counter++,this._kind=i,u===void 0){const _=this.getData();this.type=_?$.GetDataType(_):$.FLOAT}else this.type=u;const g=$.GetTypeByteLength(this.type);d?(this._size=c||(a?a/g:$.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*g,this.byteOffset=l||0):(this._size=c||a||$.DeduceStride(i),this.byteStride=a?a*g:this._buffer.byteStride||this._size*g,this.byteOffset=(l||0)*g),this.normalized=h,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?f:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?$.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/$.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/$.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*$.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){$.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case $.UVKind:case $.UV2Kind:case $.UV3Kind:case $.UV4Kind:case $.UV5Kind:case $.UV6Kind:return 2;case $.NormalKind:case $.PositionKind:return 3;case $.ColorKind:case $.ColorInstanceKind:case $.MatricesIndicesKind:case $.MatricesIndicesExtraKind:case $.MatricesWeightsKind:case $.MatricesWeightsExtraKind:case $.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?$.BYTE:e instanceof Uint8Array?$.UNSIGNED_BYTE:e instanceof Int16Array?$.SHORT:e instanceof Uint16Array?$.UNSIGNED_SHORT:e instanceof Int32Array?$.INT:e instanceof Uint32Array?$.UNSIGNED_INT:$.FLOAT}static GetTypeByteLength(e){switch(e){case $.BYTE:case $.UNSIGNED_BYTE:return 1;case $.SHORT:case $.UNSIGNED_SHORT:return 2;case $.INT:case $.UNSIGNED_INT:case $.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,n,a,o,l){if(e instanceof Array){let c=t/4;const u=i/4;for(let h=0;hh[f]=d),h}if(!(e instanceof Array||e instanceof Float32Array)||r!==0||e.length!==u)if(e instanceof Array){const h=r/4;return e.slice(h,h+u)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,r,u);{const h=e.byteOffset+r;if(h&3&&(fe.Warn("Float array must be aligned to 4-bytes border"),l=!0),l){const d=new Uint8Array(u*Float32Array.BYTES_PER_ELEMENT),f=new Uint8Array(e.buffer,h,d.length);return d.set(f),new Float32Array(d.buffer)}else return new Float32Array(e.buffer,h,u)}}return l?e.slice():e}}$._Counter=0;$.BYTE=5120;$.UNSIGNED_BYTE=5121;$.SHORT=5122;$.UNSIGNED_SHORT=5123;$.INT=5124;$.UNSIGNED_INT=5125;$.FLOAT=5126;$.PositionKind="position";$.NormalKind="normal";$.TangentKind="tangent";$.UVKind="uv";$.UV2Kind="uv2";$.UV3Kind="uv3";$.UV4Kind="uv4";$.UV5Kind="uv5";$.UV6Kind="uv6";$.ColorKind="color";$.ColorInstanceKind="instanceColor";$.MatricesIndicesKind="matricesIndices";$.MatricesWeightsKind="matricesWeights";$.MatricesIndicesExtraKind="matricesIndicesExtra";$.MatricesWeightsExtraKind="matricesWeightsExtra";class Ko{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent($.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let r;const n=se.Vector3[0],a=se.Vector3[1],o=se.Vector3[2];if(t){const c=this.pickedMesh.getVerticesData($.NormalKind);let u=i?D.FromArrayToRef(c,i[this.faceId*3]*3,n):n.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?D.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),d=i?D.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]);u=u.scale(this.bu),h=h.scale(this.bv),d=d.scale(1-this.bu-this.bv),r=new D(u.x+h.x+d.x,u.y+h.y+d.y,u.z+h.z+d.z)}else{const c=this.pickedMesh.getVerticesData($.PositionKind),u=i?D.FromArrayToRef(c,i[this.faceId*3]*3,n):n.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?D.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),d=i?D.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]),f=u.subtract(h),p=d.subtract(h);r=D.Cross(f,p)}const l=(c,u)=>{let h=c.getWorldMatrix();c.nonUniformScaling&&(se.Matrix[0].copyFrom(h),h=se.Matrix[0],h.setTranslationFromFloats(0,0,0),h.invert(),h.transposeToRef(se.Matrix[1]),h=se.Matrix[1]),D.TransformNormalToRef(u,h,u)};if(e&&l(this.pickedMesh,r),this.ray){const c=se.Vector3[0].copyFrom(r);e||l(this.pickedMesh,c),D.Dot(c,this.ray.direction)>0&&r.negateInPlace()}return r.normalize(),r}getTextureCoordinates(e=$.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=we.FromArray(i,t[this.faceId*3]*2),n=we.FromArray(i,t[this.faceId*3+1]*2),a=we.FromArray(i,t[this.faceId*3+2]*2);return r=r.scale(this.bu),n=n.scale(this.bv),a=a.scale(1-this.bu-this.bv),new we(r.x+n.x+a.x,r.y+n.y+a.y)}}class Bk{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[$.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[$.PositionKind]=new $(this._scene.getEngine(),e,$.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[$.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(r=>r!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,r=0,n=0,a=!1){var l;const o=this._scene.getEngine();for(let c=0;cc!=null),r.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let c=0,u=r.length;ct._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=Ii.LeftClick&&i<=Ii.RightClick&&(l.type=r===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,n,a){const o=this._CreateMouseEvent(e,t,i,r,n,a);switch(o.pointerId=1,o.type="wheel",o.deltaMode=iT.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case Ii.MouseWheelX:o.deltaX=r;break;case Ii.MouseWheelY:o.deltaY=r;break;case Ii.MouseWheelZ:o.deltaZ=r;break}return o}static _CreateMouseEvent(e,t,i,r,n,a){const o=this._CreateEvent(a),l=n.pollInput(e,t,Ii.Horizontal),c=n.pollInput(e,t,Ii.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,10),o.movementY=n.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=c,o.x=l,o.y=c,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,r){const n=this._CreateEvent(r);return this._CheckNonCharacterKeys(n,i),n.deviceType=ui.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=t===1?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(ui.Keyboard),r=i&&t.pollInput(ui.Keyboard,0,18)===1,n=i&&t.pollInput(ui.Keyboard,0,17)===1,a=i&&(t.pollInput(ui.Keyboard,0,91)===1||t.pollInput(ui.Keyboard,0,92)===1||t.pollInput(ui.Keyboard,0,93)===1),o=i&&t.pollInput(ui.Keyboard,0,16)===1;e.altKey=r,e.ctrlKey=n,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class z_t{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(r,n,a,o)=>{const l=jC.CreateDeviceEvent(r,n,a,o,this);i(r,n,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ui.Mouse||e===ui.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const xTe=255,ATe=Object.keys(Ii).length/2;class V_t{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Me.IsSafari(),this._usingMacOS=Ny()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=n=>{},this._keyboardUpEvent=n=>{},this._keyboardBlurEvent=n=>{},this._pointerMoveEvent=n=>{},this._pointerDownEvent=n=>{},this._pointerUpEvent=n=>{},this._pointerCancelEvent=n=>{},this._pointerWheelEvent=n=>{},this._pointerBlurEvent=n=>{},this._pointerMacOSChromeOutEvent=n=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Ny()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Ny()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=n=>{},this._gamepadDisconnectedEvent=n=>{},this._eventPrefix=Me.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const r=this._inputs[e][t];if(!r)throw`Unable to find device ${ui[e]}`;e>=ui.DualShock&&e<=ui.DualSense&&this._updateDevice(e,t,i);const n=r[i];if(n===void 0)throw`Unable to find input ${i} for device ${ui[e]} in slot ${t}`;return i===Ii.Move&&Me.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this==null?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(const t of this._inputs)if(t)for(const i in t){const r=+i,n=t[r];if(n)for(let a=0;a{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ui.Keyboard,0,xTe));const t=this._inputs[ui.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(ui.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ui.Keyboard,0,xTe));const t=this._inputs[ui.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&e.key==="Meta"&&this._metaKeys.length>0){for(const r of this._metaKeys){const n=jC.CreateDeviceEvent(ui.Keyboard,0,r,0,this,this._elementToAttachTo);t[r]=0,this._onInputChanged(ui.Keyboard,0,n)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ui.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ui.Keyboard][0];for(let t=0;t{const r=this._getPointerType(i);let n=r===ui.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===ui.Touch&&n===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)n=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(r,n);else{Me.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][n]||this._addPointerDevice(r,n,i.clientX,i.clientY);const a=this._inputs[r][n];if(a){const o=i;o.inputIndex=Ii.Move,a[Ii.Horizontal]=i.clientX,a[Ii.Vertical]=i.clientY,r===ui.Touch&&a[Ii.LeftClick]===0&&(a[Ii.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(r,n,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,a[i.button+2]=a[i.button+2]?0:1,this._onInputChanged(r,n,o))}},this._pointerDownEvent=i=>{const r=this._getPointerType(i);let n=r===ui.Mouse?0:i.pointerId;if(r===ui.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)n=o,this._activeTouchIds[o]=i.pointerId;else{Me.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][n]?r===ui.Touch&&this._onDeviceConnected(r,n):this._addPointerDevice(r,n,i.clientX,i.clientY);const a=this._inputs[r][n];if(a){const o=a[Ii.Horizontal],l=a[Ii.Vertical];if(r===ui.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch{}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch{}a[Ii.Horizontal]=i.clientX,a[Ii.Vertical]=i.clientY,a[i.button+2]=1;const c=i;c.inputIndex=i.button+2,this._onInputChanged(r,n,c),(o!==i.clientX||l!==i.clientY)&&(c.inputIndex=Ii.Move,this._onInputChanged(r,n,c))}},this._pointerUpEvent=i=>{var o,l,c,u,h;const r=this._getPointerType(i),n=r===ui.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===ui.Touch){if(n===-1)return;this._activeTouchIds[n]=-1}const a=(o=this._inputs[r])==null?void 0:o[n];if(a&&a[i.button+2]!==0){const d=a[Ii.Horizontal],f=a[Ii.Vertical];a[Ii.Horizontal]=i.clientX,a[Ii.Vertical]=i.clientY,a[i.button+2]=0;const p=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||f!==i.clientY)&&(p.inputIndex=Ii.Move,this._onInputChanged(r,n,p)),p.inputIndex=i.button+2,r===ui.Mouse&&this._mouseId>=0&&((c=(l=this._elementToAttachTo).hasPointerCapture)!=null&&c.call(l,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((h=(u=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(u,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(r,n,p),r===ui.Touch&&this._onDeviceDisconnected(r,n)}},this._pointerCancelEvent=i=>{var r,n,a,o;if(i.pointerType==="mouse"){const l=this._inputs[ui.Mouse][0];this._mouseId>=0&&((n=(r=this._elementToAttachTo).hasPointerCapture)!=null&&n.call(r,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=Ii.LeftClick;c<=Ii.BrowserForward;c++)if(l[c]===1){l[c]=0;const u=jC.CreateDeviceEvent(ui.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(ui.Mouse,0,u)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;(o=(a=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(a,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[ui.Touch][l][Ii.LeftClick]=0;const c=jC.CreateDeviceEvent(ui.Touch,l,Ii.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(ui.Touch,l,c),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(ui.Touch,l)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch{}this._pointerBlurEvent=()=>{var i,r,n,a,o;if(this.isDeviceAvailable(ui.Mouse)){const l=this._inputs[ui.Mouse][0];this._mouseId>=0&&((r=(i=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=Ii.LeftClick;c<=Ii.BrowserForward;c++)if(l[c]===1){l[c]=0;const u=jC.CreateDeviceEvent(ui.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(ui.Mouse,0,u)}}if(this.isDeviceAvailable(ui.Touch)){const l=this._inputs[ui.Touch];for(let c=0;c{const r=ui.Mouse,n=0;this._inputs[r]||(this._inputs[r]=[]),this._inputs[r][n]||(this._pointerActive=!0,this._registerDevice(r,n,ATe));const a=this._inputs[r][n];if(a){a[Ii.MouseWheelX]=i.deltaX||0,a[Ii.MouseWheelY]=i.deltaY||i.wheelDelta||0,a[Ii.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),a[Ii.MouseWheelX]!==0&&(o.inputIndex=Ii.MouseWheelX,this._onInputChanged(r,n,o)),a[Ii.MouseWheelY]!==0&&(o.inputIndex=Ii.MouseWheelY,this._onInputChanged(r,n,o)),a[Ii.MouseWheelZ]!==0&&(o.inputIndex=Ii.MouseWheelZ,this._onInputChanged(r,n,o))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(ui.Mouse)){const i=this._inputs[ui.Mouse][0];i[Ii.MouseWheelX]=0,i[Ii.MouseWheelY]=0,i[Ii.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){const n=this._inputs[e][t];i>=r.buttons.length?n[i]=r.axes[i-r.buttons.length].valueOf():n[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?ui.DualSense:ui.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ui.Xbox:e.indexOf("057e")!==-1?ui.Switch:ui.Generic}_getPointerType(e){let t=ui.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ui.Touch),t}}class Eue{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new Ae,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class G_t{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=a=>{for(let o=0;o{const o=this._registeredManagers.indexOf(a);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(ui).length/2;this._devices=new Array(t);const i=(a,o)=>{this._devices[a]||(this._devices[a]=new Array),this._devices[a][o]||(this._devices[a][o]=o);for(const l of this._registeredManagers){const c=new Eue(this._deviceInputSystem,a,o);l._addDevice(c)}},r=(a,o)=>{var l;(l=this._devices[a])!=null&&l[o]&&delete this._devices[a][o];for(const c of this._registeredManagers)c._removeDevice(a,o)},n=(a,o,l)=>{if(l)for(const c of this._registeredManagers)c._onInputChanged(a,o,l)};typeof _native<"u"?this._deviceInputSystem=new z_t(i,r,n):this._deviceInputSystem=new V_t(e,i,r,n)}dispose(){this._deviceInputSystem.dispose()}}class _9e{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){const t=Object.keys(ui).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new G_t(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new Ae(i=>{for(const r of this._devices)if(r)for(const n of r)n&&this.onDeviceConnectedObservable.notifyObserver(i,n)}),this.onDeviceDisconnectedObservable=new Ae,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var r,n;const i=(r=this._devices[e])==null?void 0:r[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(n=this._devices[e])!=null&&n[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,n;(n=(r=this._devices[e])==null?void 0:r[t])==null||n.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ui.Keyboard:case ui.Mouse:this._firstDevice[e]=0;break;case ui.Touch:case ui.DualSense:case ui.DualShock:case ui.Xbox:case ui.Switch:case ui.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=Ii.MouseWheelX&&t.inputIndex<=Ii.MouseWheelZ?yt.POINTERWHEEL:yt.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,a));let o;e?(o=new Df(a,t,e),this._setRayOnPointerInfo(e,t)):(o=new Df(a,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,a)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,he.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const r=this._scene,n=new g9e(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(n.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&n&&this._pointerOverMesh){const a=this._pointerOverMesh._getActionManagerForTrigger();a&&a.hasPointerTriggers&&(n.style.cursor=a.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=Ii.Move,!this._checkPrePointerObservable(e,i,yt.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,yt.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const a=e.pickedMesh._getActionManagerForTrigger();if(a){if(a.hasPickTriggers)switch(a.processTrigger(5,Hn.CreateNew(e.pickedMesh,t,e)),t.button){case 0:a.processTrigger(2,Hn.CreateNew(e.pickedMesh,t,e));break;case 1:a.processTrigger(4,Hn.CreateNew(e.pickedMesh,t,e));break;case 2:a.processTrigger(3,Hn.CreateNew(e.pickedMesh,t,e));break}a.hasSpecificTrigger(8)&&window.setTimeout(()=>{const o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&a&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>to.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,a.processTrigger(8,Hn.CreateNew(o.pickedMesh,t)))},to.LongPressDelay)}}else for(const a of i._pointerDownStage)e=a.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r;const n=yt.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,n),r=new Df(n,t,e),this._setRayOnPointerInfo(e,t)):r=new Df(n,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const r=new PointerEvent("pointerup",t);r.inputIndex=Ii.Move;const n=new bTe;i?n.doubleClick=!0:n.singleClick=!0,!this._checkPrePointerObservable(e,r,yt.POINTERUP)&&this._processPointerUp(e,r,n)}_processPointerUp(e,t,i){const r=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){const a=yt.POINTERPICK,o=new Df(a,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,a)}const n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,Hn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,Hn.CreateNew(e.pickedMesh,t,e));const a=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&a&&a.processTrigger(6,Hn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const n of r._pointerUpStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const n=this._pickedDownMesh._getActionManagerForTrigger(16);n&&n.processTrigger(16,Hn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const n=new Df(yt.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(n,yt.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,yt.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let a=0;if(i.singleClick?a=yt.POINTERTAP:i.doubleClick&&(a=yt.POINTERDOUBLETAP),a){const o=new Df(a,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(a)&&r.onPointerObservable.notifyObservers(o,a)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){const n=this._scene,a=n.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new _9e(a),this._initActionManager=o=>{if(!this._meshPickProceed){const l=n.skipPointerUpPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerUp?null:n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerUpPredicate,n.pointerUpFastCheck,n.cameraToUseForPointers,n.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,c)=>{if((Date.now()-this._previousStartingPointerTime>to.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){const u=this._delayedClicks[o].evt,h=yt.POINTERTAP,d=new Df(h,u,this._currentPickResult);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(h)&&n.onPointerObservable.notifyObservers(d,h),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,c,u)=>{var m,g;const h=new bTe;this._currentPickResult=null;let d=null,f=o.hasSpecificMask(yt.POINTERPICK)||l.hasSpecificMask(yt.POINTERPICK)||o.hasSpecificMask(yt.POINTERTAP)||l.hasSpecificMask(yt.POINTERTAP)||o.hasSpecificMask(yt.POINTERDOUBLETAP)||l.hasSpecificMask(yt.POINTERDOUBLETAP);!f&&Jh&&(d=this._initActionManager(d,h),d&&(f=d.hasPickTriggers));let p=!1;if(f){const _=c.button;if(h.hasSwiped=this._isPointerSwiping(),!h.hasSwiped){let y=!to.ExclusiveDoubleClickMode;if(y||(y=!o.hasSpecificMask(yt.POINTERDOUBLETAP)&&!l.hasSpecificMask(yt.POINTERDOUBLETAP),y&&!Jh.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(y=!d.hasSpecificTrigger(6)))),y)(Date.now()-this._previousStartingPointerTime>to.DoubleClickDelay||_!==this._previousButtonPressed)&&(h.singleClick=!0,u(h,this._currentPickResult),p=!0);else{const x={evt:c,clickInfo:h,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,_,h,u),to.DoubleClickDelay)};this._delayedClicks[_]=x}let v=o.hasSpecificMask(yt.POINTERDOUBLETAP)||l.hasSpecificMask(yt.POINTERDOUBLETAP);!v&&Jh.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(v=d.hasSpecificTrigger(6))),v&&(_===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>to.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>to.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=Ii.MouseWheelX&&o.inputIndex<=Ii.MouseWheelZ?yt.POINTERWHEEL:yt.POINTERMOVE)||!n.cameraToUseForPointers&&!n.activeCamera)return;if(n.skipPointerMovePicking){this._processPointerMove(new Ko,o);return}n.pointerMovePredicate||(n.pointerMovePredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(c.enablePointerMoveEvents||n.constantlyUpdateMeshUnderPointer||c._getActionManagerForTrigger()!==null)&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&c.layerMask)!==0));const l=n._registeredActions>0||n.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var c;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,to.ExclusiveDoubleClickMode){for(let u=0;uu.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&u.layerMask)!==0)),this._pickedDownMesh=null;let l;n.skipPointerDownPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerDown?l=new Ko:l=n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerDownPredicate,n.pointerDownFastCheck,n.cameraToUseForPointers,n.pointerDownTrianglePredicate),this._processPointerDown(l,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),n.preventDefaultOnPointerUp&&r&&(o.preventDefault(),r.focus()),this._initClickEvent(n.onPrePointerObservable,n.onPointerObservable,o,(l,c)=>{if(n.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,yt.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&n.onPrePointerObservable.hasSpecificMask(yt.POINTERTAP)&&this._checkPrePointerObservable(null,o,yt.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&n.onPrePointerObservable.hasSpecificMask(yt.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,yt.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!n.cameraToUseForPointers&&!n.activeCamera)&&(n.pointerUpPredicate||(n.pointerUpPredicate=u=>u.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&u.layerMask)!==0)),!this._meshPickProceed&&(Jh&&Jh.HasTriggers||this._checkForPicking()||n.onPointerUp)&&this._initActionManager(null,l),c||(c=this._currentPickResult),this._processPointerUp(c,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const l=lg.KEYDOWN;if(n.onPreKeyboardObservable.hasObservers()){const c=new vue(l,o);if(n.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const c=new oZ(l,o);n.onKeyboardObservable.notifyObservers(c,l)}n.actionManager&&n.actionManager.processTrigger(14,Hn.CreateNewFromScene(n,o))},this._onKeyUp=o=>{const l=lg.KEYUP;if(n.onPreKeyboardObservable.hasObservers()){const c=new vue(l,o);if(n.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const c=new oZ(l,o);n.onKeyboardObservable.notifyObservers(c,l)}n.actionManager&&n.actionManager.processTrigger(15,Hn.CreateNewFromScene(n,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===ui.Mouse?o.onInputChangedObservable.add(l=>{this._originMouseEvent=l,l.inputIndex===Ii.LeftClick||l.inputIndex===Ii.MiddleClick||l.inputIndex===Ii.RightClick||l.inputIndex===Ii.BrowserBack||l.inputIndex===Ii.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===Ii.Move?this._onPointerMove(l):(l.inputIndex===Ii.MouseWheelX||l.inputIndex===Ii.MouseWheelY||l.inputIndex===Ii.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===ui.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===Ii.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===Ii.Move&&this._onPointerMove(l)}):o.deviceType===ui.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const n=this._meshUnderPointerId[t];let a;n&&(a=n._getActionManagerForTrigger(10),a&&a.processTrigger(10,Hn.CreateNew(n,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,a=e._getActionManagerForTrigger(9),a&&a.processTrigger(9,Hn.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}to.DragMovementThreshold=10;to.LongPressDelay=500;to.DoubleClickDelay=300;to.ExclusiveDoubleClickMode=!1;class io{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){io.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){io.Enabled&&(this._startMonitoringTime=Or.Now)}endMonitoring(e=!0){if(!io.Enabled)return;e&&this.fetchNewFrame();const t=Or.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=Or.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}io.Enabled=!0;class Xl{constructor(e,t,i,r){this.normal=new D(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Xl(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Xl._TmpMatrix;e.invertToRef(t);const i=t.m,r=this.normal.x,n=this.normal.y,a=this.normal.z,o=this.d,l=r*i[0]+n*i[1]+a*i[2]+o*i[3],c=r*i[4]+n*i[5]+a*i[6]+o*i[7],u=r*i[8]+n*i[9]+a*i[10]+o*i[11],h=r*i[12]+n*i[13]+a*i[14]+o*i[15];return new Xl(l,c,u,h)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const r=t.x-e.x,n=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,c=i.z-e.z,u=n*c-a*l,h=a*o-r*c,d=r*l-n*o,f=Math.sqrt(u*u+h*h+d*d);let p;return f!==0?p=1/f:p=0,this.normal.x=u*p,this.normal.y=h*p,this.normal.z=d*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return D.Dot(this.normal,e)<=t}signedDistanceTo(e){return D.Dot(e,this.normal)+this.d}static FromArray(e){return new Xl(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const r=new Xl(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){const i=new Xl(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const r=-(t.x*e.x+t.y*e.y+t.z*e.z);return D.Dot(i,t)+r}}Xl._TmpMatrix=he.Identity();class Od{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Xl(0,0,0,0));return Od.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Od.GetNearPlaneToRef(e,t[0]),Od.GetFarPlaneToRef(e,t[1]),Od.GetLeftPlaneToRef(e,t[2]),Od.GetRightPlaneToRef(e,t[3]),Od.GetTopPlaneToRef(e,t[4]),Od.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class hz{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}hz._UniqueIdCounter=1;class Us{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Us.FALLOFF_DEFAULT=0;Us.FALLOFF_PHYSICAL=1;Us.FALLOFF_GLTF=2;Us.FALLOFF_STANDARD=3;Us.LIGHTMAP_DEFAULT=0;Us.LIGHTMAP_SPECULAR=1;Us.LIGHTMAP_SHADOWSONLY=2;Us.INTENSITYMODE_AUTOMATIC=0;Us.INTENSITYMODE_LUMINOUSPOWER=1;Us.INTENSITYMODE_LUMINOUSINTENSITY=2;Us.INTENSITYMODE_ILLUMINANCE=3;Us.INTENSITYMODE_LUMINANCE=4;Us.LIGHTTYPEID_POINTLIGHT=0;Us.LIGHTTYPEID_DIRECTIONALLIGHT=1;Us.LIGHTTYPEID_SPOTLIGHT=2;Us.LIGHTTYPEID_HEMISPHERICLIGHT=3;class W_t{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Tue;(function(s){s[s.BackwardCompatible=0]="BackwardCompatible",s[s.Intermediate=1]="Intermediate",s[s.Aggressive=2]="Aggressive"})(Tue||(Tue={}));class gt extends Oa{static DefaultMaterialFactory(e){throw vi("StandardMaterial")}static CollisionCoordinatorFactory(){throw vi("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return to.DragMovementThreshold}static set DragMovementThreshold(e){to.DragMovementThreshold=e}static get LongPressDelay(){return to.LongPressDelay}static set LongPressDelay(e){to.LongPressDelay=e}static get DoubleClickDelay(){return to.DoubleClickDelay}static set DoubleClickDelay(e){to.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return to.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){to.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,n=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return se.Vector4[0].set(r.x,r.y,r.z,n?-1:1),e&&(i?e.setFloat3(t,se.Vector4[0].x,se.Vector4[0].y,se.Vector4[0].z):e.setVector4(t,se.Vector4[0])),se.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=TFe(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=gt.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=gt.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new to(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ze(.2,.2,.3,1),this.ambientColor=new Re(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new Ae,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new Ae,this._onDisposeObserver=null,this.onBeforeRenderObservable=new Ae,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new Ae,this.onAfterRenderCameraObservable=new Ae,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new Ae,this.onAfterAnimationsObservable=new Ae,this.onBeforeDrawPhaseObservable=new Ae,this.onAfterDrawPhaseObservable=new Ae,this.onReadyObservable=new Ae,this.onBeforeCameraRenderObservable=new Ae,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new Ae,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new Ae,this.onAfterActiveMeshesEvaluationObservable=new Ae,this.onBeforeParticlesRenderingObservable=new Ae,this.onAfterParticlesRenderingObservable=new Ae,this.onDataLoadedObservable=new Ae,this.onNewCameraAddedObservable=new Ae,this.onCameraRemovedObservable=new Ae,this.onNewLightAddedObservable=new Ae,this.onLightRemovedObservable=new Ae,this.onNewGeometryAddedObservable=new Ae,this.onGeometryRemovedObservable=new Ae,this.onNewTransformNodeAddedObservable=new Ae,this.onTransformNodeRemovedObservable=new Ae,this.onNewMeshAddedObservable=new Ae,this.onMeshRemovedObservable=new Ae,this.onNewSkeletonAddedObservable=new Ae,this.onSkeletonRemovedObservable=new Ae,this.onNewMaterialAddedObservable=new Ae,this.onNewMultiMaterialAddedObservable=new Ae,this.onMaterialRemovedObservable=new Ae,this.onMultiMaterialRemovedObservable=new Ae,this.onNewTextureAddedObservable=new Ae,this.onTextureRemovedObservable=new Ae,this.onBeforeRenderTargetsRenderObservable=new Ae,this.onAfterRenderTargetsRenderObservable=new Ae,this.onBeforeStepObservable=new Ae,this.onAfterStepObservable=new Ae,this.onActiveCameraChanged=new Ae,this.onActiveCamerasChanged=new Ae,this.onBeforeRenderingGroupObservable=new Ae,this.onAfterRenderingGroupObservable=new Ae,this.onMeshImportedObservable=new Ae,this.onAnimationFileImportedObservable=new Ae,this._registeredForLateAnimationBindings=new q2(256),this._pointerPickingConfiguration=new W_t,this.onPrePointerObservable=new Ae,this.onPointerObservable=new Ae,this.onPreKeyboardObservable=new Ae,this.onKeyboardObservable=new Ae,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=gt.FOGMODE_NONE,this.fogColor=new Re(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new D(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new q2(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new io,this._activeIndices=new io,this._activeParticles=new io,this._activeBones=new io,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new no(256),this._processedMaterials=new no(256),this._renderTargets=new q2(256),this._materialsRenderTargets=new q2(256),this._activeParticleSystems=new no(256),this._activeSkeletons=new q2(32),this._softwareSkinnedMeshes=new q2(32),this._activeAnimatables=new Array,this._transformMatrix=he.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Ga.Create(),this._beforeClearStage=Ga.Create(),this._beforeRenderTargetClearStage=Ga.Create(),this._gatherRenderTargetsStage=Ga.Create(),this._gatherActiveCameraRenderTargetsStage=Ga.Create(),this._isReadyForMeshStage=Ga.Create(),this._beforeEvaluateActiveMeshStage=Ga.Create(),this._evaluateSubMeshStage=Ga.Create(),this._preActiveMeshStage=Ga.Create(),this._cameraDrawRenderTargetStage=Ga.Create(),this._beforeCameraDrawStage=Ga.Create(),this._beforeRenderTargetDrawStage=Ga.Create(),this._beforeRenderingGroupDrawStage=Ga.Create(),this._beforeRenderingMeshStage=Ga.Create(),this._afterRenderingMeshStage=Ga.Create(),this._afterRenderingGroupDrawStage=Ga.Create(),this._afterCameraDrawStage=Ga.Create(),this._afterCameraPostProcessStage=Ga.Create(),this._afterRenderTargetDrawStage=Ga.Create(),this._afterRenderTargetPostProcessStage=Ga.Create(),this._afterRenderStage=Ga.Create(),this._pointerMoveStage=Ga.Create(),this._pointerDownStage=Ga.Create(),this._pointerUpStage=Ga.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||Rt.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Rt._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Wl(this),Bk&&(this.postProcessManager=new Bk(this)),To()&&this.attachControl(),this._createUbo(),lr&&(this._imageProcessingConfiguration=new lr),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var a,o;if(this._isDisposed)return!1;let t;const i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=((a=this.activeCamera)==null?void 0:a.renderPassId)??r;let n=!0;for(this._pendingData.length>0&&(n=!1),(o=this.prePassRenderer)==null||o.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&n&&(n=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const h of this._isReadyForMeshStage)h.action(l,c)||(n=!1);if(!e)continue;const u=l.material||this.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const h of l.subMeshes){const d=h.getMaterial();d&&d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}else u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const l of this.activeCameras)l.isReady(!0)||(n=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(n=!1));for(const l of this.particleSystems)l.isReady()||(n=!1);if(this.layers)for(const l of this.layers)l.isReady()||(n=!1);return i.areAllEffectsReady()||(n=!1),i.currentRenderPassId=r,n}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);i!==-1&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_checkIsReady(e=!1){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=Or.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){!i&&!r&&this._multiviewSceneUbo&&(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Od.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Od.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new zt(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return hz.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(i=>{this.addMesh(i)}))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return i!==-1&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(r=>{this.removeMesh(r)}),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){const i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(t!==-1){for(const i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(t!==-1&&ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const r=this.getLightById(e);if(r)return r;const n=this.getCameraById(e);if(n)return n;const a=this.getBoneById(e);return a||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const r=this.getLightByName(e);if(r)return r;const n=this.getCameraByName(e);if(n)return n;const a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=n,this._skipEvaluateActiveMeshesCompletely=e,r)for(let a=0;ae.dispose())}_evaluateActiveMeshes(){var i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const r=this._activeMeshes.length;for(let n=0;n0&&n.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||n.alwaysSelectAsActiveMesh||n.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(n),this.activeCamera._activeMeshes.push(n),a!==n&&a._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(n);n._activate(this._renderId,!1)&&(n.isAnInstance?n._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=n):a._internalAbstractMeshDataInfo._onlyForInstances=!1,a._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(n,a)),n._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let r=0;r0){const r=this.getActiveSubMeshCandidates(t),n=r.length;i=i||n===1;for(let a=0;a0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const o of this._gatherActiveCameraRenderTargetsStage)o.action(this._renderTargets);let n=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Me.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let o=0;o0),this._renderId++}for(const o of this._cameraDrawRenderTargetStage)n=o.action(this.activeCamera)||n;this._intermediateRendering=!1}this._engine.currentRenderPassId=((a=e.outputRenderTarget)==null?void 0:a.renderPassId)??e.renderPassId??0,n&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const o of this._beforeCameraDrawStage)o.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),r.snapshotRendering&&r.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const o of this._afterCameraDrawStage)o.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const o=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,o)}for(const o of this._afterCameraPostProcessStage)o.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(r.trigger===13&&r._executeCurrent(Hn.CreateNew(t,void 0,a)),(!t.actionManager.hasSpecificTrigger(13,c=>{const u=c.mesh?c.mesh:c;return a===u})||r.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(gt.MinDeltaTime,Math.min(this._engine.getDeltaTime(),gt.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let r=0;const n=this._engine.getLockstepMaxSteps();let a=Math.floor(e/t);for(a=Math.min(a,n);e>0&&r0)for(let o=0;o0),this._intermediateRendering=!0;for(let o=0;o0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(r==null?void 0:r.renderPassId)??0,this.activeCamera=r,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const o of this._beforeClearStage)o.action();this._clearFrameBuffer(this.activeCamera);for(const o of this._gatherRenderTargetsStage)o.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const o of this._afterRenderStage)o.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let o=0;o{n.onAnimationEndObservable.clear(),n.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const n of e)n.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(n){fe.Error("An error occurred while calling onDisposeObservable!",n)}if(this.detachControl(),this._engine.getInputElement())for(let n=0;nn.dispose(!0)),this._disposeList(this.transformNodes,n=>n.dispose(!0));const i=this.cameras;this._disposeList(i),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let r=this._engine.scenes.indexOf(this);r>-1&&this._engine.scenes.splice(r,1),Rt._LastCreatedScene===this&&(this._engine.scenes.length>0?Rt._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Rt._LastCreatedScene=null),r=this._engine._virtualScenes.indexOf(this),r>-1&&this._engine._virtualScenes.splice(r,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(r=>r.dispose());for(const r of i)t(r);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(r=>{if(r.computeWorldMatrix(!0),!r.subMeshes||r.subMeshes.length===0||r.infiniteDistance)return;const n=r.getBoundingInfo(),a=n.boundingBox.minimumWorld,o=n.boundingBox.maximumWorld;D.CheckExtends(a,t,i),D.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,r,n=!1){throw vi("Ray")}createPickingRayToRef(e,t,i,r,n,a=!1,o=!1){throw vi("Ray")}createPickingRayInCameraSpace(e,t,i){throw vi("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw vi("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,r,n,a){const o=vi("Ray",!0);return o&&fe.Warn(o),new Ko}pickWithBoundingInfo(e,t,i,r,n){const a=vi("Ray",!0);return a&&fe.Warn(a),new Ko}pickWithRay(e,t,i,r){throw vi("Ray")}multiPick(e,t,i,r,n){throw vi("Ray")}multiPickWithRay(e,t,i){throw vi("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const r=[];for(const n in e){const a=e[n];Br&&Br.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,n,a,o){const l=Uv(e,t,i,r?this.offlineProvider:void 0,n,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}_loadFileAsync(e,t,i,r,n){return new Promise((a,o)=>{this._loadFile(e,l=>{a(l)},t,i,r,(l,c)=>{o(c)},n)})}_requestFile(e,t,i,r,n,a,o){const l=EJ(e,t,i,r?this.offlineProvider:void 0,n,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}_requestFileAsync(e,t,i,r,n){return new Promise((a,o)=>{this._requestFile(e,l=>{a(l)},t,i,r,l=>{o(l)},n)})}_readFile(e,t,i,r,n){const a=iw(e,t,i,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}_readFileAsync(e,t,i){return new Promise((r,n)=>{this._readFile(e,a=>{r(a)},t,i,a=>{n(a)})})}getPerfCollector(){throw vi("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}gt.FOGMODE_NONE=0;gt.FOGMODE_EXP=1;gt.FOGMODE_EXP2=2;gt.FOGMODE_LINEAR=3;gt.MinDeltaTime=1;gt.MaxDeltaTime=1e3;ve("BABYLON.Scene",gt);class js extends ns{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){e.updateFlag===this._localMatrix.updateFlag&&!this._needToCompose||(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,n=null,a=null,o=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=(r==null?void 0:r.clone())??he.Identity(),this._restMatrix=n??this._localMatrix.clone(),this._bindMatrix=a??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new he,this._absoluteBindMatrix=new he,this._absoluteInverseBindMatrix=new he,this._finalMatrix=new he,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const i=this.parent.children.indexOf(this);i!==-1&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=se.Vector3[0],t=se.Quaternion[0],i=se.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??Pe.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=D.Zero(),this._localRotation=Pe.Zero(),this._localPosition=D.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,he.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let i=0;i-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(n)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const a=this._runtimeAnimations;for(let o=a.length-1;o>=0;o--){const l=a[o];e&&l.animation.name!=e||t&&!t(l.target)||(l.dispose(),a.splice(o,1))}a.length==0&&(i||this._scene._activeAnimatables.splice(n,1),r||this._raiseOnAnimationEnd())}}else{const n=this._scene._activeAnimatables.indexOf(this);if(n>-1){i||this._scene._activeAnimatables.splice(n,1);const a=this._runtimeAnimations;for(let o=0;o{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=e),!0;if(this._localDelayOffset===null?(this._localDelayOffset=e,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,this._weight===0)return!0;let t=!1;const i=this._runtimeAnimations;let r;for(r=0;r0)return;this._animationTimeLast=e}this.deltaTime=s!==void 0?s:this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(t.length===0)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let r=0;rs.playOrder-e.playOrder)};gt.prototype.beginWeightedAnimation=function(s,e,t,i=1,r,n=1,a,o,l,c,u=!1){const h=this.beginAnimation(s,e,t,r,n,a,o,!1,l,c,u);return h.weight=i,h};gt.prototype.beginAnimation=function(s,e,t,i,r=1,n,a,o=!0,l,c,u=!1){e>t&&r>0&&(r*=-1),o&&this.stopAnimation(s,void 0,l),a||(a=new yge(this,s,e,t,i,r,n,void 0,c,u));const h=l?l(s):!0;if(s.animations&&h&&a.appendAnimations(s,s.animations),s.getAnimatables){const d=s.getAnimatables();for(let f=0;fi&&n>0)n*=-1;else if(i>t&&n<0){const u=i;i=t,t=u}return new yge(this,s,t,i,r,n,a,e,o,l)};gt.prototype.beginDirectHierarchyAnimation=function(s,e,t,i,r,n,a,o,l,c=!1){const u=s.getDescendants(e),h=[];h.push(this.beginDirectAnimation(s,t,i,r,n,a,o,l,c));for(const d of u)h.push(this.beginDirectAnimation(d,t,i,r,n,a,o,l,c));return h};gt.prototype.getAnimatableByTarget=function(s){for(let e=0;e0?l:-l,r),f.scaleAndAddToRef(l,t)}r.normalize()}for(let h=0;h0)r.copyFrom(i);else if(s.animations.length===1){if(Pe.SlerpToRef(i,t.currentValue,Math.min(1,s.totalWeight),r),s.totalAdditiveWeight===0)return r}else if(s.animations.length>1){let n=1,a,o;if(s.totalWeight<1){const c=1-s.totalWeight;a=[],o=[],a.push(i),o.push(c)}else{if(s.animations.length===2&&(Pe.SlerpToRef(s.animations[0].currentValue,s.animations[1].currentValue,s.animations[1].weight/s.totalWeight,e),s.totalAdditiveWeight===0))return e;a=[],o=[],n=s.totalWeight}for(let c=0;c=a&&g.frame<=o&&(i?(y=g.value.clone(),d?(_=y.getTranslation(),y.setTranslation(_.scaleInPlace(f))):p&&r?(_=y.getTranslation(),y.setTranslation(_.multiplyInPlace(r))):y=g.value):y=g.value,m.push({frame:g.frame+t,value:y}));return this.animations[0].createRange(e,a+t,o+t),!0};class K_t{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=tt.ANIMATIONLOOPMODE_CYCLE}}var Mue;(function(s){s[s.CW=0]="CW",s[s.CCW=1]="CCW"})(Mue||(Mue={}));let v9e=class{static Interpolate(e,t,i,r,n){const a=1-3*r+3*t,o=3*r-6*t,l=3*t;let c=e;for(let u=0;u<5;u++){const h=c*c,d=h*c,f=a*d+o*h+l*c,p=1/(3*a*h+2*o*c+l);c-=(f-e)*p,c=Math.min(1,Math.max(0,c))}return 3*Math.pow(1-c,2)*c*i+3*(1-c)*Math.pow(c,2)*n+Math.pow(c,3)}};class zm{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),r=Math.atan2(i.y,i.x);return new zm(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new zm(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=At.Clamp(r,-1,1);const n=Math.acos(r);return new zm(n)}static FromRadians(e){return new zm(e)}static FromDegrees(e){return new zm(e*Math.PI/180)}}class y9e{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const r=Math.pow(t.x,2)+Math.pow(t.y,2),n=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new we((n*(t.y-i.y)-a*(e.y-t.y))/o,((e.x-t.x)*a-(t.x-i.x)*n)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=zm.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let c=zm.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),u=zm.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),u-c>180&&(u-=360),u-c<-180&&(u+=360),this.orientation=c-l<0?0:1,this.angle=zm.FromDegrees(this.orientation===0?l-u:u-l)}}class Qw{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new we(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new we(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,n=36){if(this.closed)return this;const a=this._points[this._points.length-1],o=new we(e,t),l=new we(i,r),c=new y9e(a,o,l);let u=c.angle.radians()/n;c.orientation===0&&(u*=-1);let h=c.startAngle.radians()+u;for(let d=0;d(1-l)*(1-l)*c+2*l*(1-l)*u+l*l*h,o=this._points[this._points.length-1];for(let l=0;l<=n;l++){const c=l/n,u=a(c,o.x,e,i),h=a(c,o.y,t,r);this.addLineTo(u,h)}return this}addBezierCurveTo(e,t,i,r,n,a,o=36){if(this.closed)return this;const l=(u,h,d,f,p)=>(1-u)*(1-u)*(1-u)*h+3*u*(1-u)*(1-u)*d+3*u*u*(1-u)*f+u*u*u*p,c=this._points[this._points.length-1];for(let u=0;u<=o;u++){const h=u/o,d=l(h,c.x,e,i,n),f=l(h,c.y,t,r,a);this.addLineTo(d,f)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let r=i-1,n=0;nNumber.EPSILON){if(c<0&&(a=this._points[n],l=-l,o=this._points[r],c=-c),e.yo.y)continue;if(e.y===a.y&&e.x===a.x)return!0;{const u=c*(e.x-a.x)-l*(e.y-a.y);if(u===0)return!0;if(u<0)continue;t=!t}}else{if(e.y!==a.y)continue;if(o.x<=e.x&&e.x<=a.x||a.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,r=0;r1)return we.Zero();const t=e*this.length();let i=0;for(let r=0;r=i&&t<=c){const u=l.normalize(),h=t-i;return new we(a.x+u.x*h,a.y+u.y*h)}i=c}return we.Zero()}static StartingAt(e,t){return new Qw(e,t)}}class qS{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:D.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:he.Identity()};for(let n=0;nt){const c=e;e=t,t=c}const i=this.getCurve(),r=this.getPointAt(e);let n=this.getPreviousPointIndexAt(e);const a=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(n++,l.push(r)),l.push(...i.slice(n,o)),(t!==1||e===1)&&l.push(a),new qS(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(r===0&&(r=1),t==null){let n;At.WithinEpsilon(Math.abs(e.y)/r,1,ci)?At.WithinEpsilon(Math.abs(e.x)/r,1,ci)?At.WithinEpsilon(Math.abs(e.z)/r,1,ci)?n=D.Zero():n=new D(0,0,1):n=new D(1,0,0):n=new D(0,-1,0),i=D.Cross(e,n)}else i=D.Cross(e,t),D.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r=i[0],n,a=0;const o=e*this.length();for(let l=1;lo){const h=(a-o)/c,d=r.subtract(n),f=n.add(d.scaleInPlace(h));return this._setPointAtData(e,1-h,f,l-1,t)}r=n}return this._pointAtData}_setPointAtData(e,t,i,r,n){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=n,n&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=he.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),n=this._binormals[e].clone(),a=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),c=Pe.RotationQuaternionFromAxis(r,n,i),u=Pe.RotationQuaternionFromAxis(o,l,a);Pe.Slerp(c,u,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class Jp{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;const n=[],a=(o,l,c,u)=>(1-o)*(1-o)*l+2*o*(1-o)*c+o*o*u;for(let o=0;o<=r;o++)n.push(new D(a(o/r,e.x,t.x,i.x),a(o/r,e.y,t.y,i.y),a(o/r,e.z,t.z,i.z)));return new Jp(n)}static CreateCubicBezier(e,t,i,r,n){n=n>3?n:4;const a=[],o=(l,c,u,h,d)=>(1-l)*(1-l)*(1-l)*c+3*l*(1-l)*(1-l)*u+3*l*l*(1-l)*h+l*l*l*d;for(let l=0;l<=n;l++)a.push(new D(o(l/n,e.x,t.x,i.x,r.x),o(l/n,e.y,t.y,i.y,r.y),o(l/n,e.z,t.z,i.z,r.z)));return new Jp(a)}static CreateHermiteSpline(e,t,i,r,n){const a=[],o=1/n;for(let l=0;l<=n;l++)a.push(D.Hermite(e,t,i,r,l*o));return new Jp(a)}static CreateCatmullRomSpline(e,t,i){const r=[],n=1/t;let a=0;if(i){const o=e.length;for(let l=0;l=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}ya.EASINGMODE_EASEIN=0;ya.EASINGMODE_EASEOUT=1;ya.EASINGMODE_EASEINOUT=2;class x9e extends ya{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class A9e extends ya{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class H_t extends ya{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const r=Math.pow(i,t),n=1-i,a=(1-r)/n+r*.5,o=e*a,l=Math.log(-o*(1-i)+1)/Math.log(i),c=Math.floor(l),u=c+1,h=(1-Math.pow(i,c))/(n*a),d=(1-Math.pow(i,u))/(n*a),f=(h+d)*.5,p=e-f,m=f-h;return-Math.pow(1/i,t-c)/(m*m)*(p-m)*(p+m)}}class j_t extends ya{easeInCore(e){return e*e*e}}class X_t extends ya{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return r==0?t=e:t=(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class b9e extends ya{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class Y_t extends ya{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class xge extends ya{easeInCore(e){return e*e}}class Q_t extends ya{easeInCore(e){return e*e*e*e}}class $_t extends ya{easeInCore(e){return e*e*e*e*e}}class Age extends ya{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Z_t extends ya{constructor(e=0,t=0,i=1,r=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=r}easeInCore(e){return v9e.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class MJ{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new MJ(this.frame,this.action,this.onlyOnce)}}class C9e{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Lm{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(!this.mask&&!e){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let t=0;t0)){for(let t=0;ta&&(a=l.to);const o=new Lm(e[0].name+"_merged",e[0]._scene,r);for(const l of e){i&&l.normalize(n,a);for(const c of l.targetedAnimations)o.addTargetedAnimation(c.animation,c.target);t&&l.dispose()}return o}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new Ae,this.onAnimationLoopObservable=new Ae,this.onAnimationGroupLoopObservable=new Ae,this.onAnimationGroupEndObservable=new Ae,this.onAnimationGroupPauseObservable=new Ae,this.onAnimationGroupPlayObservable=new Ae,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||Rt.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new C9e;i.animation=e,i.target=t;const r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;ie){const l={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};n.splice(0,0,l)}if(o.frame{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,n){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,a),this._animatables.push(l)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0?this._scene._activeAnimatables[i++]=n:e&&this._checkAnimationGroupEnded(n,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const t=this._parentContainer.animationGroups.indexOf(this);t>-1&&this._parentContainer.animationGroups.splice(t,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){const i=this._animatables.indexOf(e);i>-1&&this._animatables.splice(i,1),this._animatables.length===0&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const r=new Lm(e||this.name,this._scene,this._weight,this._playOrder);r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask;for(const n of this._targetedAnimations)r.addTargetedAnimation(i?n.animation.clone():n.animation,t?t(n.target):n.target);return r}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tm[0].frame&&(c=m[0].frame),u=t&&m<=i||n&&g.frame>=t&&g.frame<=i){const _={frame:g.frame,value:g.value.clone?g.value.clone():g.value,inTangent:g.inTangent,outTangent:g.outTangent,interpolation:g.interpolation,lockedTangent:g.lockedTangent};p===Number.MAX_VALUE&&(p=_.frame),_.frame-=p,f.push(_)}}if(f.length===0){l.splice(c,1),c--;continue}a>f[0].frame&&(a=f[0].frame),o1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach(e=>e(this)),this}onchange(e){return this._onchange.push(e),this}}var Iue;(function(s){s[s.Include=0]="Include",s[s.Exclude=1]="Exclude"})(Iue||(Iue={}));class J_t{constructor(e,t=0){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e)){for(const t of e)this._targetNames.add(t);return}this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e)){for(const t of e)this._targetNames.delete(t);return}this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(this.mode===0)}}function kk(s,e,t){try{const i=s.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function S9e(s=25){let e;return(t,i,r)=>{const n=performance.now();e===void 0||n-e>s?(e=n,setTimeout(()=>{kk(t,i,r)},0)):kk(t,i,r)}}function bge(s,e,t,i,r){const n=()=>{let a;const o=l=>{l.done?t(l.value):a===void 0?a=!0:n()};do a=void 0,!r||!r.aborted?e(s,o,i):i(new Error("Aborted")),a===void 0&&(a=!1);while(a)};n()}function RJ(s,e){let t;return bge(s,kk,i=>t=i,i=>{throw i},e),t}function IJ(s,e,t){return new Promise((i,r)=>{bge(s,e,i,r,t)})}function E9e(s,e){return(...t)=>RJ(s(...t),e)}function e2t(s,e,t){return(...i)=>IJ(s(...i),e,t)}class uc{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new uc(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new uc(this.x,this.y,this.width,this.height)}}class Nt extends ns{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===Nt.PERSPECTIVE_CAMERA)this.fovMode===Nt.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,r=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??r)-(this.orthoBottom??-r)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i,!1),this._position=D.Zero(),this._upVector=D.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=Nt.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new uc(0,0,1,1),this.layerMask=268435455,this.fovMode=Nt.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Nt.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new Ae,this.onProjectionMatrixChangedObservable=new Ae,this.onAfterCheckInputsObservable=new Ae,this.onRestoreStateObservable=new Ae,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new he,this._postProcesses=new Array,this._activeMeshes=new no(256),this._globalPosition=D.Zero(),this._computedViewMatrix=he.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=he.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Pe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(fe.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return he.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var n,a,o;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),r=t.useReverseDepthBuffer;if(this.mode===Nt.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let l;i.useRightHandedSystem?l=he.PerspectiveFovRHToRef:l=he.PerspectiveFovLHToRef,l(this.fov,t.getAspectRatio(this),r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Nt.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,r)}else{const l=t.getRenderWidth()/2,c=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?he.ObliqueOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):he.OrthoOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?he.ObliqueOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):he.OrthoOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(n=this.oblique)==null?void 0:n.angle,this._cache.obliqueLength=(a=this.oblique)==null?void 0:a.length,this._cache.obliqueOffset=(o=this.oblique)==null?void 0:o.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){const t=this,i=this;return(t.radius||(i.target?D.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Od.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Od.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;return this.rigCameras.forEach(r=>{r._updateFrustumPlanes(),i=i||e.isInFrustum(r._frustumPlanes)}),i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw vi("Ray")}getForwardRayToRef(e,t=100,i,r){throw vi("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const r=this._rigCameras.pop();r&&r.dispose()}if(this._parentContainer){const r=this._parentContainer.cameras.indexOf(this);r>-1&&this._parentContainer.cameras.splice(r,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==Nt.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let r=this._postProcesses.length;for(;--r>=0;){const n=this._postProcesses[r];n&&n.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Me.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Nt.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const r=this.createRigCamera(this.name+"_R",1);r&&(r._isRightCamera=!0),i&&r&&(this._rigCameras.push(i),this._rigCameras.push(r))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return he.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=Me.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eNt._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,r=Nt.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=qe.Parse(r,e,t);if(e.parentId!==void 0&&(n._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=D.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(D.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(D.FromArray(e.target)),e.cameraRigMode){const a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(let a=0;a{throw vi("UniversalCamera")};Nt.PERSPECTIVE_CAMERA=0;Nt.ORTHOGRAPHIC_CAMERA=1;Nt.FOVMODE_VERTICAL_FIXED=0;Nt.FOVMODE_HORIZONTAL_FIXED=1;Nt.RIG_MODE_NONE=0;Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Nt.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Nt.RIG_MODE_VR=20;Nt.RIG_MODE_CUSTOM=22;Nt.ForceAttachControlToAlwaysPreventDefault=!1;F([Pn("position")],Nt.prototype,"_position",void 0);F([Pn("upVector")],Nt.prototype,"_upVector",void 0);F([X()],Nt.prototype,"orthoLeft",null);F([X()],Nt.prototype,"orthoRight",null);F([X()],Nt.prototype,"orthoBottom",null);F([X()],Nt.prototype,"orthoTop",null);F([X()],Nt.prototype,"fov",void 0);F([X()],Nt.prototype,"projectionPlaneTilt",void 0);F([X()],Nt.prototype,"minZ",void 0);F([X()],Nt.prototype,"maxZ",void 0);F([X()],Nt.prototype,"inertia",void 0);F([X()],Nt.prototype,"mode",null);F([X()],Nt.prototype,"layerMask",void 0);F([X()],Nt.prototype,"fovMode",void 0);F([X()],Nt.prototype,"cameraRigMode",void 0);F([X()],Nt.prototype,"interaxialDistance",void 0);F([X()],Nt.prototype,"isStereoscopicSideBySide",void 0);class lZ{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class ed{constructor(e,t,i){this.vectors=vh(8,D.Zero),this.center=D.Zero(),this.centerWorld=D.Zero(),this.extendSize=D.Zero(),this.extendSizeWorld=D.Zero(),this.directions=vh(3,D.Zero),this.vectorsWorld=vh(8,D.Zero),this.minimumWorld=D.Zero(),this.maximumWorld=D.Zero(),this.minimum=D.Zero(),this.maximum=D.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const r=e.x,n=e.y,a=e.z,o=t.x,l=t.y,c=t.z,u=this.vectors;this.minimum.copyFromFloats(r,n,a),this.maximum.copyFromFloats(o,l,c),u[0].copyFromFloats(r,n,a),u[1].copyFromFloats(o,l,c),u[2].copyFromFloats(o,n,a),u[3].copyFromFloats(r,l,a),u[4].copyFromFloats(r,n,c),u[5].copyFromFloats(o,l,a),u[6].copyFromFloats(r,l,c),u[7].copyFromFloats(o,n,c),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||he.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=ed._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);const n=r*e,a=i.scaleInPlace(n*.5),o=this.center.subtractToRef(a,t[1]),l=this.center.addToRef(a,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,r=this.directions,n=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)n[o].copyFrom(a[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){const l=n[o];D.TransformCoordinatesToRef(a[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}D.FromArrayToRef(e.m,0,r[0]),D.FromArrayToRef(e.m,4,r[1]),D.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return ed.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return ed.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,r=t.x,n=t.y,a=t.z,o=i.x,l=i.y,c=i.z,u=e.x,h=e.y,d=e.z,f=-ci;return!(o-uu-r||l-hh-n||c-dd-a)}intersectsSphere(e){return ed.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,r=this.maximumWorld,n=i.x,a=i.y,o=i.z,l=r.x,c=r.y,u=r.z,h=e.x,d=e.y,f=e.z,p=t.x,m=t.y,g=t.z;return!(lp||cm||ug)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){const n=ed._TmpVector3[0];return D.ClampToRef(i,e,t,n),D.DistanceSquared(i,n)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const r=t[i];for(let n=0;n<8;++n)if(r.dotCoordinate(e[n])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0;const n=t[i];for(let a=0;a<8;++a)if(n.dotCoordinate(e[a])>=0){r=!1;break}if(r)return!1}return!0}}ed._TmpVector3=vh(3,D.Zero);class qm{constructor(e,t,i){this.center=D.Zero(),this.centerWorld=D.Zero(),this.minimum=D.Zero(),this.maximum=D.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const r=D.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=r*.5,this._update(i||he.IdentityReadOnly)}scale(e){const t=this.radius*e,i=qm._TmpVector3,r=i[0].setAll(t),n=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(n,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{D.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=qm._TmpVector3[0];D.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=D.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=D.Dot(e.centerWorld,s),r=Math.abs(D.Dot(e.directions[0],s))*e.extendSize.x,n=Math.abs(D.Dot(e.directions[1],s))*e.extendSize.y,a=Math.abs(D.Dot(e.directions[2],s))*e.extendSize.z,o=r+n+a;t.min=i-o,t.max=i+o},zh=(s,e,t)=>(CTe(s,e,Tne),CTe(s,t,Mne),!(Tne.min>Mne.max||Mne.min>Tne.max));class Oc{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new ed(e,t,i),this.boundingSphere=new qm(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=Oc._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=Oc._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=D.Minimize(this.minimum,e),i=D.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=se.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=se.Vector3[0];return D.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),D.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,Oc._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(e)||!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!qm.Intersects(this.boundingSphere,e.boundingSphere)||!ed.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,r=e.boundingBox;return!(!zh(i.directions[0],i,r)||!zh(i.directions[1],i,r)||!zh(i.directions[2],i,r)||!zh(r.directions[0],i,r)||!zh(r.directions[1],i,r)||!zh(r.directions[2],i,r)||!zh(D.Cross(i.directions[0],r.directions[0]),i,r)||!zh(D.Cross(i.directions[0],r.directions[1]),i,r)||!zh(D.Cross(i.directions[0],r.directions[2]),i,r)||!zh(D.Cross(i.directions[1],r.directions[0]),i,r)||!zh(D.Cross(i.directions[1],r.directions[1]),i,r)||!zh(D.Cross(i.directions[1],r.directions[2]),i,r)||!zh(D.Cross(i.directions[2],r.directions[0]),i,r)||!zh(D.Cross(i.directions[2],r.directions[1]),i,r)||!zh(D.Cross(i.directions[2],r.directions[2]),i,r))}}Oc._TmpVector3=vh(2,D.Zero);class PJ{static extractMinAndMaxIndexed(e,t,i,r,n,a){for(let o=i;o!Array.isArray(s)&&!Array.isArray(e))],PJ,"extractMinAndMaxIndexed",null);F([l_.filter((...[s])=>!Array.isArray(s))],PJ,"extractMinAndMax",null);function T9e(s,e,t,i,r=null){const n=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return PJ.extractMinAndMaxIndexed(s,e,t,i,n,a),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:n,maximum:a}}function JS(s,e,t,i=null,r){const n=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),PJ.extractMinAndMax(s,e,t,r,n,a),i&&(n.x-=n.x*i.x+i.y,n.y-=n.y*i.x+i.y,n.z-=n.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:n,maximum:a}}class Ro{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,t!==void 0&&(this.defines=t),i&&((r=this.drawContext)==null||r.reset())}dispose(){var e;(e=this.drawContext)==null||e.dispose()}}class wl{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())==null?void 0:e.defines}set materialDefines(e){const t=this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Ro(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])==null||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:((e=this._getDrawWrapper())==null?void 0:e.effect)??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){const n=this._drawWrapper;n.setEffect(e,t,r),i!==void 0&&(n.materialContext=i),e||(n.defines=null,n.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t==null||t.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,r,n,a,o,l=!0){return new wl(e,t,i,r,n,a,o,l)}constructor(e,t,i,r,n,a,o,l=!0,c=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=n,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=a,this._renderingMesh=o||a,c&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,l&&(this.refreshBoundingInfo(),a.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){const i=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==i&&(this._currentMaterial=i,this.resetDrawCache()),i}}else return e?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData($.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(this.indexStart===0&&this.indexCount===t.length){const r=this._renderingMesh.getBoundingInfo();i={minimum:r.minimum.clone(),maximum:r.maximum.clone()}}else i=T9e(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Oc(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let r=this.indexStart;rl&&(l=d)}return new wl(e,o,l-o+1,t,i,r,n,a)}}class GB{}class at{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=E9e(this._applyToCoroutine.bind(this)),this.uniqueId=at._UniqueIDGenerator,at._UniqueIDGenerator++}set(e,t){switch(e.length||fe.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case $.PositionKind:this.positions=e;break;case $.NormalKind:this.normals=e;break;case $.TangentKind:this.tangents=e;break;case $.UVKind:this.uvs=e;break;case $.UV2Kind:this.uvs2=e;break;case $.UV3Kind:this.uvs3=e;break;case $.UV4Kind:this.uvs4=e;break;case $.UV5Kind:this.uvs5=e;break;case $.UV6Kind:this.uvs6=e;break;case $.ColorKind:this.colors=e;break;case $.MatricesIndicesKind:this.matricesIndices=e;break;case $.MatricesWeightsKind:this.matricesWeights=e;break;case $.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case $.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData($.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData($.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData($.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData($.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData($.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData($.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData($.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData($.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData($.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData($.ColorKind,this.colors,t),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData($.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData($.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData($.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData($.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const r=e;r.subMeshes=[];for(const n of this.materialInfos)new wl(n.materialIndex,n.verticesStart,n.verticesCount,n.indexStart,n.indexCount,r)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData($.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData($.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData($.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData($.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData($.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData($.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData($.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData($.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData($.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData($.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData($.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData($.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData($.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData($.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){const n=se.Vector3[0],a=se.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return RJ(this._mergeCoroutine(void 0,a,t,!1,i,r,n))}*_mergeCoroutine(e,t,i=!1,r,n,a=!1,o=!1){var f,p;this._validate();let l=t.map(m=>m.vertexData),c=this;if(o)for(const m of l)m&&(m._validate(),!this.normals&&m.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&m.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&m.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&m.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&m.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&m.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&m.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&m.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&m.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&m.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&m.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&m.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&m.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const m of l)if(m){if(o)this.normals&&!m.normals&&(m.normals=new Float32Array(m.positions.length)),this.tangents&&!m.tangents&&(m.tangents=new Float32Array(m.positions.length/3*4)),this.uvs&&!m.uvs&&(m.uvs=new Float32Array(m.positions.length/3*2)),this.uvs2&&!m.uvs2&&(m.uvs2=new Float32Array(m.positions.length/3*2)),this.uvs3&&!m.uvs3&&(m.uvs3=new Float32Array(m.positions.length/3*2)),this.uvs4&&!m.uvs4&&(m.uvs4=new Float32Array(m.positions.length/3*2)),this.uvs5&&!m.uvs5&&(m.uvs5=new Float32Array(m.positions.length/3*2)),this.uvs6&&!m.uvs6&&(m.uvs6=new Float32Array(m.positions.length/3*2)),this.colors&&!m.colors&&(m.colors=new Float32Array(m.positions.length/3*4),m.colors.fill(1)),this.matricesIndices&&!m.matricesIndices&&(m.matricesIndices=new Float32Array(m.positions.length/3*4)),this.matricesWeights&&!m.matricesWeights&&(m.matricesWeights=new Float32Array(m.positions.length/3*4)),this.matricesIndicesExtra&&!m.matricesIndicesExtra&&(m.matricesIndicesExtra=new Float32Array(m.positions.length/3*4)),this.matricesWeightsExtra&&!m.matricesWeightsExtra&&(m.matricesWeightsExtra=new Float32Array(m.positions.length/3*4));else if(m._validate(),!this.normals!=!m.normals||!this.tangents!=!m.tangents||!this.uvs!=!m.uvs||!this.uvs2!=!m.uvs2||!this.uvs3!=!m.uvs3||!this.uvs4!=!m.uvs4||!this.uvs5!=!m.uvs5||!this.uvs6!=!m.uvs6||!this.colors!=!m.colors||!this.matricesIndices!=!m.matricesIndices||!this.matricesWeights!=!m.matricesWeights||!this.matricesIndicesExtra!=!m.matricesIndicesExtra||!this.matricesWeightsExtra!=!m.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let m=0,g=0,_=0;const y=[];let v=null;const x=[];for(const b of this.splitBasedOnMaterialID())x.push({vertexData:b,transform:e});for(const b of t)if(b.vertexData)for(const C of b.vertexData.splitBasedOnMaterialID())x.push({vertexData:C,transform:b.transform});x.sort((b,C)=>{const T=b.vertexData.materialInfos?b.vertexData.materialInfos[0].materialIndex:0,w=C.vertexData.materialInfos?C.vertexData.materialInfos[0].materialIndex:0;return T>w?1:T===w?0:-1});for(const b of x){const C=b.vertexData;if(C.materialInfos?m=C.materialInfos[0].materialIndex:m=0,v&&v.materialIndex===m)v.indexCount+=C.indices.length,v.verticesCount+=C.positions.length/3;else{const T=new GB;T.materialIndex=m,T.indexStart=g,T.indexCount=C.indices.length,T.verticesStart=_,T.verticesCount=C.positions.length/3,y.push(T),v=T}g+=C.indices.length,_+=C.positions.length/3}const A=x.splice(0,1)[0];c=A.vertexData,e=A.transform,l=x.map(b=>b.vertexData),t=x,this.materialInfos=y}const u=l.reduce((m,g)=>{var _;return m+(((_=g.indices)==null?void 0:_.length)??0)},((f=c.indices)==null?void 0:f.length)??0);let d=n||l.some(m=>m.indices===c.indices)?(p=c.indices)==null?void 0:p.slice():c.indices;if(u>0){let m=(d==null?void 0:d.length)??0;if(d||(d=new Array(u)),d.length!==u){if(Array.isArray(d))d.length=u;else{const _=i||d instanceof Uint32Array?new Uint32Array(u):new Uint16Array(u);_.set(d),d=_}e&&e.determinant()<0&&at._FlipFaces(d,0,m)}let g=c.positions?c.positions.length/3:0;for(const{vertexData:_,transform:y}of t)if(_.indices){for(let v=0;v<_.indices.length;v++)d[m+v]=_.indices[v]+g;y&&y.determinant()<0&&at._FlipFaces(d,m,_.indices.length),g+=_.positions.length/3,m+=_.indices.length,r&&(yield)}}return this.indices=d,this.positions=at._MergeElement($.PositionKind,c.positions,e,t.map(m=>[m.vertexData.positions,m.transform])),r&&(yield),c.normals&&(this.normals=at._MergeElement($.NormalKind,c.normals,e,t.map(m=>[m.vertexData.normals,m.transform])),r&&(yield)),c.tangents&&(this.tangents=at._MergeElement($.TangentKind,c.tangents,e,t.map(m=>[m.vertexData.tangents,m.transform])),r&&(yield)),c.uvs&&(this.uvs=at._MergeElement($.UVKind,c.uvs,e,t.map(m=>[m.vertexData.uvs,m.transform])),r&&(yield)),c.uvs2&&(this.uvs2=at._MergeElement($.UV2Kind,c.uvs2,e,t.map(m=>[m.vertexData.uvs2,m.transform])),r&&(yield)),c.uvs3&&(this.uvs3=at._MergeElement($.UV3Kind,c.uvs3,e,t.map(m=>[m.vertexData.uvs3,m.transform])),r&&(yield)),c.uvs4&&(this.uvs4=at._MergeElement($.UV4Kind,c.uvs4,e,t.map(m=>[m.vertexData.uvs4,m.transform])),r&&(yield)),c.uvs5&&(this.uvs5=at._MergeElement($.UV5Kind,c.uvs5,e,t.map(m=>[m.vertexData.uvs5,m.transform])),r&&(yield)),c.uvs6&&(this.uvs6=at._MergeElement($.UV6Kind,c.uvs6,e,t.map(m=>[m.vertexData.uvs6,m.transform])),r&&(yield)),c.colors&&(this.colors=at._MergeElement($.ColorKind,c.colors,e,t.map(m=>[m.vertexData.colors,m.transform])),(c.hasVertexAlpha!==void 0||t.some(m=>m.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=c.hasVertexAlpha||t.some(m=>m.vertexData.hasVertexAlpha)),r&&(yield)),c.matricesIndices&&(this.matricesIndices=at._MergeElement($.MatricesIndicesKind,c.matricesIndices,e,t.map(m=>[m.vertexData.matricesIndices,m.transform])),r&&(yield)),c.matricesWeights&&(this.matricesWeights=at._MergeElement($.MatricesWeightsKind,c.matricesWeights,e,t.map(m=>[m.vertexData.matricesWeights,m.transform])),r&&(yield)),c.matricesIndicesExtra&&(this.matricesIndicesExtra=at._MergeElement($.MatricesIndicesExtraKind,c.matricesIndicesExtra,e,t.map(m=>[m.vertexData.matricesIndicesExtra,m.transform])),r&&(yield)),c.matricesWeightsExtra&&(this.matricesWeightsExtra=at._MergeElement($.MatricesWeightsExtraKind,c.matricesWeightsExtra,e,t.map(m=>[m.vertexData.matricesWeightsExtra,m.transform]))),this}static _MergeElement(e,t,i,r){const n=r.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&n.length==0)return t;if(!t)return this._MergeElement(e,n[0][0],n[0][1],n.slice(1));const a=n.reduce((l,c)=>l+c[0].length,t.length),o=e===$.PositionKind?at._TransformVector3Coordinates:e===$.NormalKind?at._TransformVector3Normals:e===$.TangentKind?at._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(a);l.set(t),i&&o(l,i,0,t.length);let c=t.length;for(const[u,h]of n)l.set(u,c),h&&o(l,h,c,u.length),c+=u.length;return l}else{const l=new Array(a);for(let u=0;u{const a=$.DeduceStride(r);if(n.length%a!==0)throw new Error("The "+r+"s array count must be a multiple of "+a);return n.length/a},t=e($.PositionKind,this.positions),i=(r,n)=>{const a=e(r,n);if(a!==t)throw new Error("The "+r+"s element count ("+a+") does not match the positions count ("+t+")")};this.normals&&i($.NormalKind,this.normals),this.tangents&&i($.TangentKind,this.tangents),this.uvs&&i($.UVKind,this.uvs),this.uvs2&&i($.UV2Kind,this.uvs2),this.uvs3&&i($.UV3Kind,this.uvs3),this.uvs4&&i($.UV4Kind,this.uvs4),this.uvs5&&i($.UV5Kind,this.uvs5),this.uvs6&&i($.UV6Kind,this.uvs6),this.colors&&i($.ColorKind,this.colors),this.matricesIndices&&i($.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i($.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i($.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i($.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return at.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return at._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return at._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const r=new at;if(e.isVerticesDataPresent($.PositionKind)&&(r.positions=e.getVerticesData($.PositionKind,t,i)),e.isVerticesDataPresent($.NormalKind)&&(r.normals=e.getVerticesData($.NormalKind,t,i)),e.isVerticesDataPresent($.TangentKind)&&(r.tangents=e.getVerticesData($.TangentKind,t,i)),e.isVerticesDataPresent($.UVKind)&&(r.uvs=e.getVerticesData($.UVKind,t,i)),e.isVerticesDataPresent($.UV2Kind)&&(r.uvs2=e.getVerticesData($.UV2Kind,t,i)),e.isVerticesDataPresent($.UV3Kind)&&(r.uvs3=e.getVerticesData($.UV3Kind,t,i)),e.isVerticesDataPresent($.UV4Kind)&&(r.uvs4=e.getVerticesData($.UV4Kind,t,i)),e.isVerticesDataPresent($.UV5Kind)&&(r.uvs5=e.getVerticesData($.UV5Kind,t,i)),e.isVerticesDataPresent($.UV6Kind)&&(r.uvs6=e.getVerticesData($.UV6Kind,t,i)),e.isVerticesDataPresent($.ColorKind)){const n=e.geometry||e,a=n.getVertexBuffer($.ColorKind),o=n.getVerticesData($.ColorKind,t,i);if(a.getSize()===3){const l=new Float32Array(o.length*4/3);for(let c=0,u=0;c!Array.isArray(s))],at,"_TransformVector3Coordinates",null);F([l_.filter((...[s])=>!Array.isArray(s))],at,"_TransformVector3Normals",null);F([l_.filter((...[s])=>!Array.isArray(s))],at,"_TransformVector4Normals",null);F([l_.filter((...[s])=>!Array.isArray(s))],at,"_FlipFaces",null);class Eo{static get ForceFullSceneLoadingForIncremental(){return Eo._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Eo._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Eo._ShowLoadingScreen}static set ShowLoadingScreen(e){Eo._ShowLoadingScreen=e}static get loggingLevel(){return Eo._LoggingLevel}static set loggingLevel(e){Eo._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Eo._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Eo._CleanBoneMatrixWeights=e}}Eo._ForceFullSceneLoadingForIncremental=!1;Eo._ShowLoadingScreen=!0;Eo._CleanBoneMatrixWeights=!1;Eo._LoggingLevel=0;let Qr=!1;const t2t={get UseOpenGLOrientationForUV(){return Qr},set UseOpenGLOrientationForUV(s){Qr=s}};function M9e(s,e,t,i,r,n,a,o){const l=e*$.GetTypeByteLength(t),c=a*e;if(o.length!==c)throw new Error("Output length is not valid");if(t!==$.FLOAT||r!==l){$.ForEach(s,i,r,e,t,c,n,(u,h)=>o[h]=u);return}if(s instanceof Array){const u=i/4;o.set(s,u)}else if(s instanceof ArrayBuffer){const u=new Float32Array(s,i,c);o.set(u)}else{const u=s.byteOffset+i;if(u%4){fe.Warn("CopyFloatData: copied misaligned data."),o.set(new Float32Array(s.buffer.slice(u,u+c*4)));return}const d=new Float32Array(s.buffer,u,c);o.set(d)}}class So{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new So(So.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,n=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Rt.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),n&&(this.applyToMesh(n),n.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));const n=new $(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(n)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;const n=this._meshes,a=n.length;if(r===$.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new D(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let c=0;c65535);for(const r of this._meshes)r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(const r of this._meshes)r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,r=i.indexOf(e);r!==-1&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData($.PositionKind),!e))return;this._extend=JS(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)t===1&&this._vertexBuffers[i].create(),i===$.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const r=this._meshes,n=r.length;for(let a=0;a0){for(let r=0;r0){for(let r=0;r0){for(let r=0;r-1&&this._parentContainer.geometries.splice(r,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new at;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const o=new Float32Array(e,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);t.setVerticesData($.PositionKind,o,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){const o=new Float32Array(e,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);t.setVerticesData($.NormalKind,o,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){const o=new Float32Array(e,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);t.setVerticesData($.TangentKind,o,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){const o=new Float32Array(e,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);if(Qr)for(let l=1;l0){const o=new Float32Array(e,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);if(Qr)for(let l=1;l0){const o=new Float32Array(e,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);if(Qr)for(let l=1;l0){const o=new Float32Array(e,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);if(Qr)for(let l=1;l0){const o=new Float32Array(e,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);if(Qr)for(let l=1;l0){const o=new Float32Array(e,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);if(Qr)for(let l=1;l0){const o=new Float32Array(e,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);t.setVerticesData($.ColorKind,o,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),l=[];for(let c=0;c>8),l.push((u&16711680)>>16),l.push(u>>24&255)}t.setVerticesData($.MatricesIndicesKind,l,!1)}if(a.matricesIndicesExtraAttrDesc&&a.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,a.matricesIndicesExtraAttrDesc.offset,a.matricesIndicesExtraAttrDesc.count),l=[];for(let c=0;c>8),l.push((u&16711680)>>16),l.push(u>>24&255)}t.setVerticesData($.MatricesIndicesExtraKind,l,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);t.setVerticesData($.MatricesWeightsKind,o,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){const o=new Int32Array(e,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);t.setIndices(o,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){const o=new Int32Array(e,a.subMeshesAttrDesc.offset,a.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData($.MatricesIndicesKind,a,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData($.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const a=[];for(let o=0;o>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData($.MatricesIndicesExtraKind,a,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(So._CleanMatricesWeights(e,t),t.setVerticesData($.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData($.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let a=0;a-1){const h=t.getScene().getLastSkeletonById(e.skeletonId);if(!h)return;r=h.bones.length}else return;const n=t.getVerticesData($.MatricesIndicesKind),a=t.getVerticesData($.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,c=e.numBoneInfluencer,u=o.length;for(let h=0;hc-1)&&(f=c-1),d>.001){const p=1/d;for(let m=0;m<4;m++)o[h+m]*=p;if(l)for(let m=0;m<4;m++)l[h+m]*=p}else f>=4?(l[h+f-4]=1-d,a[h+f-4]=r):(o[h+f]=1-d,n[h+f]=r)}t.setVerticesData($.MatricesIndicesKind,n),e.matricesWeightsExtra&&t.setVerticesData($.MatricesIndicesExtraKind,a)}static Parse(e,t,i){const r=new So(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,Br&&Br.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new Oc(D.FromArray(e.boundingBoxMinimum),D.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push($.UVKind),e.hasUVs2&&r._delayInfo.push($.UV2Kind),e.hasUVs3&&r._delayInfo.push($.UV3Kind),e.hasUVs4&&r._delayInfo.push($.UV4Kind),e.hasUVs5&&r._delayInfo.push($.UV5Kind),e.hasUVs6&&r._delayInfo.push($.UV6Kind),e.hasColors&&r._delayInfo.push($.ColorKind),e.hasMatricesIndices&&r._delayInfo.push($.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push($.MatricesWeightsKind),r._delayLoadingFunction=at.ImportVertexData):at.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}const i2t=he.Compose(D.One(),Pe.FromEulerAngles(0,Math.PI,0),D.Zero());class _t extends ns{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&_t.BILLBOARDMODE_USE_POSITION)!==0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==_t.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new D(0,0,1),this._up=new D(0,1,0),this._right=new D(1,0,0),this._position=D.Zero(),this._rotation=D.Zero(),this._rotationQuaternion=null,this._scaling=D.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=_t.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=he.Zero(),this._usePivotMatrix=!1,this._absolutePosition=D.Zero(),this._absoluteScaling=D.Zero(),this._absoluteRotationQuaternion=Pe.Identity(),this._pivotMatrix=he.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new Ae,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return D.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return D.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return D.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=he.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==_t.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=he.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(const n of this.getChildTransformNodes(!0))n.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||Pe.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){const n=se.Matrix[0];this.parent.getWorldMatrix().invertToRef(n),D.TransformCoordinatesFromFloatsToRef(t,i,r,n,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=D.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=se.Matrix[0];return this._localMatrix.invertToRef(e),D.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=D.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,n=0){const a=_t._LookAtVectorCache,o=n===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,a),this.setDirection(a,t,i,r),n===1&&this.parent)if(this.rotationQuaternion){const l=se.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const c=se.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=se.Quaternion[0];Pe.FromEulerVectorToRef(this.rotation,l);const c=se.Matrix[0];l.toRotationMatrix(c);const u=se.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(u),u.invert(),c.multiplyToRef(u,c),l.fromRotationMatrix(c),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=D.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return D.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){const n=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,a);return this.rotationQuaternion?Pe.RotationYawPitchRollToRef(n+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=n+t,this.rotation.z=r),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==1){const r=se.Matrix[0];i.invertToRef(r),e=D.TransformCoordinates(e,r)}return this.setPivotMatrix(he.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=D.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=D.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),D.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const r=se.Quaternion[0],n=se.Vector3[0],a=se.Vector3[1],o=se.Matrix[1];he.IdentityToRef(o);const l=se.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=_t._TmpRotation,Pe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),he.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(a,r,n,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(n),this.parent=e,i&&this.setPivotMatrix(he.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let r;if(!i||i===0)r=Pe.RotationAxisToRef(e,t,_t._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);else{if(this.parent){const n=this.parent.getWorldMatrix(),a=se.Matrix[0];n.invertToRef(a),e=D.TransformNormal(e,a),n.determinant()<0&&(t*=-1)}r=Pe.RotationAxisToRef(e,t,_t._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Pe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const r=se.Vector3[0],n=se.Vector3[1],a=se.Vector3[2],o=se.Quaternion[0],l=se.Matrix[0],c=se.Matrix[1],u=se.Matrix[2],h=se.Matrix[3];return e.subtractToRef(this.position,r),he.TranslationToRef(r.x,r.y,r.z,l),he.TranslationToRef(-r.x,-r.y,-r.z,c),he.RotationAxisToRef(t,i,u),c.multiplyToRef(u,h),h.multiplyToRef(l,h),h.decompose(n,o,a),this.position.addInPlace(a),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const r=e.scale(t);if(!i||i===0){const n=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(n)}else this.setAbsolutePosition(this.getAbsolutePosition().add(r));return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=se.Quaternion[1],Pe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));const n=se.Quaternion[0];return Pe.RotationYawPitchRollToRef(t,e,i,n),r.multiplyInPlace(n),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==_t.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const n=this._getEffectiveParent(),a=_t._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const c=t.getWorldMatrix(),u=new D(c.m[12],c.m[13],c.m[14]);o=_t._TmpTranslation,o.copyFromFloats(this._position.x+u.x,this._position.y+u.y,this._position.z+u.z)}a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(Pe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=_t._TmpRotation,Pe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const c=se.Matrix[1];he.ScalingToRef(a.x,a.y,a.z,c);const u=se.Matrix[0];l.toRotationMatrix(u),this._pivotMatrix.multiplyToRef(c,se.Matrix[4]),se.Matrix[4].multiplyToRef(u,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else he.ComposeToRef(a,l,o,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),r.useBillboardPath){if(this._transformToBoneReferal){const d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),se.Matrix[7])}else se.Matrix[7].copyFrom(n.getWorldMatrix());const c=se.Vector3[5],u=se.Vector3[6],h=se.Quaternion[0];se.Matrix[7].decompose(u,h,c),he.ScalingToRef(u.x,u.y,u.z,se.Matrix[7]),se.Matrix[7].setTranslation(c),_t.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(h,c),this._localMatrix.setTranslation(c)),this._localMatrix.multiplyToRef(se.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const c=this.parent;c.getSkeleton().prepare(),this._localMatrix.multiplyToRef(c.getFinalMatrix(),se.Matrix[6]),se.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(r.useBillboardPath&&t&&this.billboardMode&&!r.useBillboardPosition){const c=se.Vector3[0];if(this._worldMatrix.getTranslationToRef(c),se.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&se.Matrix[1].multiplyToRef(i2t,se.Matrix[1]),se.Matrix[1].setTranslationFromFloats(0,0,0),se.Matrix[1].invertToRef(se.Matrix[0]),(this.billboardMode&_t.BILLBOARDMODE_ALL)!==_t.BILLBOARDMODE_ALL){se.Matrix[0].decompose(void 0,se.Quaternion[0],void 0);const u=se.Vector3[1];se.Quaternion[0].toEulerAnglesToRef(u),(this.billboardMode&_t.BILLBOARDMODE_X)!==_t.BILLBOARDMODE_X&&(u.x=0),(this.billboardMode&_t.BILLBOARDMODE_Y)!==_t.BILLBOARDMODE_Y&&(u.y=0),(this.billboardMode&_t.BILLBOARDMODE_Z)!==_t.BILLBOARDMODE_Z&&(u.z=0),he.RotationYawPitchRollToRef(u.y,u.x,u.z,se.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(se.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(se.Vector3[0])}else if(r.useBillboardPath&&t&&r.useBillboardPosition){const c=se.Vector3[0];this._worldMatrix.getTranslationToRef(c);const u=t.globalPosition;this._worldMatrix.invertToRef(se.Matrix[1]);const h=se.Vector3[1];D.TransformCoordinatesToRef(u,se.Matrix[1],h),h.normalize();const d=-Math.atan2(h.z,h.x)+Math.PI/2,f=Math.sqrt(h.x*h.x+h.z*h.z),p=-Math.atan2(h.y,f);if(Pe.RotationYawPitchRollToRef(d,p,0,se.Quaternion[0]),(this.billboardMode&_t.BILLBOARDMODE_ALL)!==_t.BILLBOARDMODE_ALL){const m=se.Vector3[1];se.Quaternion[0].toEulerAnglesToRef(m),(this.billboardMode&_t.BILLBOARDMODE_X)!==_t.BILLBOARDMODE_X&&(m.x=0),(this.billboardMode&_t.BILLBOARDMODE_Y)!==_t.BILLBOARDMODE_Y&&(m.y=0),(this.billboardMode&_t.BILLBOARDMODE_Z)!==_t.BILLBOARDMODE_Z&&(m.z=0),he.RotationYawPitchRollToRef(m.y,m.x,m.z,se.Matrix[0])}else he.FromQuaternionToRef(se.Quaternion[0],se.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(se.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(se.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=he.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew _t(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){const n=this.getDescendants(!0);for(let a=0;anew _t(e.name,t),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(he.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(he.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let n=0;n(!t||t(r))&&r instanceof _t),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const i=this.getChildTransformNodes(!0);for(const r of i)r.parent=null,r.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,n=null;t&&(this.rotationQuaternion?(n=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const a=this.getHierarchyBoundingVectors(e,i),o=a.max.subtract(a.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;const c=1/l;return this.scaling.scaleInPlace(c),t&&(this.rotationQuaternion&&n?this.rotationQuaternion.copyFrom(n):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}_t.BILLBOARDMODE_NONE=0;_t.BILLBOARDMODE_X=1;_t.BILLBOARDMODE_Y=2;_t.BILLBOARDMODE_Z=4;_t.BILLBOARDMODE_ALL=7;_t.BILLBOARDMODE_USE_POSITION=128;_t.BillboardUseParentOrientation=!1;_t._TmpRotation=Pe.Zero();_t._TmpScaling=D.Zero();_t._TmpTranslation=D.Zero();_t._LookAtVectorCache=new D(0,0,0);_t._RotationAxisCache=new Pe;F([Pn("position")],_t.prototype,"_position",void 0);F([Pn("rotation")],_t.prototype,"_rotation",void 0);F([VFe("rotationQuaternion")],_t.prototype,"_rotationQuaternion",void 0);F([Pn("scaling")],_t.prototype,"_scaling",void 0);F([X("billboardMode")],_t.prototype,"_billboardMode",void 0);F([X()],_t.prototype,"scalingDeterminant",void 0);F([X("infiniteDistance")],_t.prototype,"_infiniteDistance",void 0);F([X()],_t.prototype,"ignoreNonUniformScaling",void 0);F([X()],_t.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class R9e{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new D(0,0,0),this._diffPositionForCollisions=new D(0,0,0),this._collisionResponse=!0}}var Pue;(function(s){s[s.LOCAL=0]="LOCAL",s[s.WORLD=1]="WORLD",s[s.BONE=2]="BONE"})(Pue||(Pue={}));let Da=class{};Da.X=new D(1,0,0);Da.Y=new D(0,1,0);Da.Z=new D(0,0,1);var wue;(function(s){s[s.X=0]="X",s[s.Y=1]="Y",s[s.Z=2]="Z"})(wue||(wue={}));function r2t(s,e,t){let i=null;switch(e){case $.PositionKind:i=r=>r.getPositions();break;case $.NormalKind:i=r=>r.getNormals();break;case $.TangentKind:i=r=>r.getTangents();break;case $.UVKind:i=r=>r.getUVs();break;default:return}for(let r=0;r0&&(he.FromFloat32ArrayToRefScaled(t,Math.floor(i[d+f]*16),p,c),l.addToSelf(c));if(n&&a)for(f=0;f<4;f++)p=a[d+f],p>0&&(he.FromFloat32ArrayToRefScaled(t,Math.floor(n[d+f]*16),p,c),l.addToSelf(c));u(s[h],s[h+1],s[h+2],l,o),o.toArray(s,h)}}class n2t{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=D.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class a2t{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new n2t,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new R9e,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class Li extends _t{static get BILLBOARDMODE_NONE(){return _t.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return _t.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return _t.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return _t.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return _t.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return _t.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get inheritVisibility(){return this._internalAbstractMeshDataInfo._inheritVisibility}set inheritVisibility(e){this._internalAbstractMeshDataInfo._inheritVisibility=e}get isVisible(){if(!this._isVisible||!this.inheritVisibility||!this._parentNode)return this._isVisible;if(this._isVisible){let e=this._parentNode;for(;e;){const t=e.isVisible;if(typeof t<"u")return t;e=e.parent}}return this._isVisible}set isVisible(e){this._isVisible=e}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new a2t,this._waitingMaterialId=null,this.cullingStrategy=Li.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new Ae,this.onCollisionPositionChangeObservable=new Ae,this.onMaterialChangedObservable=new Ae,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this._isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Re.Red(),this.outlineWidth=.02,this.overlayColor=Re.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new D(.5,1,.5),this.ellipsoidOffset=new D(0,0,0),this.edgesWidth=1,this.edgesColor=new Ze(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new Ae,this._onCollisionPositionChange=(i,r,n=null)=>{r.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ge.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),n&&this.onCollideObservable.notifyObservers(n),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new zt(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+(this.getClassName()!=="InstancedMesh"?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==_t.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(const t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let r=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new Oc(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent($.MatricesIndicesKind)&&this.isVerticesDataPresent($.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===_t.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const r=new he;(this.rotationQuaternion?this.rotationQuaternion:Pe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);const a=D.Zero(),o=this.definedFacingForward?-1:1;return D.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const r=this.definedFacingForward?1:-1;return new D(e*r,t,i*r)}_refreshBoundingInfo(e,t){if(e){const i=JS(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Oc(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i{if(r){const o=r._vertexData||(r._vertexData={});return o[a]||this.copyVerticesData(a,o),o[a]}return this.getVerticesData(a)};if(t||(t=n(i)),!t)return null;if(r?(r._outputData?r._outputData.set(t):r._outputData=new Float32Array(t),t=r._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&r2t(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const a=n($.MatricesIndicesKind),o=n($.MatricesWeightsKind);if(o&&a){const l=this.numBoneInfluencers>4,c=l?n($.MatricesIndicesExtraKind):null,u=l?n($.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this);Li._ApplySkeleton(t,i,h,a,o,c,u)}}if(e.updatePositionsArray!==!1&&i===$.PositionKind){const a=this._internalAbstractMeshDataInfo._positions||[],o=a.length;if(a.length=t.length/3,o1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const r=this.getBoundingInfo(),n=e.getBoundingInfo();if(r.intersects(n,t))return!0;if(i){for(const a of this.getChildMeshes())if(a.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const n=e.verticesStart,a=e.verticesStart+e.verticesCount;for(let o=n;o1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=se.Matrix[0],i=se.Matrix[1];return he.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,n,a=!1){const o=new Ko,l=this.getClassName(),c=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,u=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(u.boundingSphere,c)||!e.intersectsBox(u.boundingBox,c)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:D.Distance(e.origin,u.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let h=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),f=d.length;let p=!1;for(let m=0;m1&&!a&&!g.canIntersects(e))continue;const _=g.intersects(e,this._positions,this.getIndices(),t,i);if(_&&(t||!h||_.distanceo!==this&&o.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let l=o.includedOnlyMeshes.indexOf(this);l!==-1&&o.includedOnlyMeshes.splice(l,1),l=o.excludedMeshes.indexOf(this),l!==-1&&o.excludedMeshes.splice(l,1);const c=o.getShadowGenerators();if(c){const u=c.values();for(let h=u.next();h.done!==!0;h=u.next()){const f=h.value.getShadowMap();f&&f.renderList&&(l=f.renderList.indexOf(this),l!==-1&&f.renderList.splice(l,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const a=r.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,a.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),a.wipeCaches(),r.removeMesh(this),this._parentContainer){const o=this._parentContainer.meshes.indexOf(this);o>-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){o=!0;break}o?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(o,l){return l.sqDistance-o.sqDistance},!e.facetDepthSortFrom){const o=this.getScene().activeCamera;e.facetDepthSortFrom=o?o.position:D.Zero()}e.depthSortedFacets=[];for(let o=0;oci?n.maximum.x-n.minimum.x:ci,e.bbSize.y=n.maximum.y-n.minimum.y>ci?n.maximum.y-n.minimum.y:ci,e.bbSize.z=n.maximum.z-n.minimum.z>ci?n.maximum.z-n.minimum.z:ci;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=n,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),D.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&at.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let l=0;ln.subDiv.max||o<0||o>n.subDiv.max||l<0||l>n.subDiv.max?null:n.facetPartitioning[a+n.subDiv.max*o+n.subDiv.max*n.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,r,n=!1,a=!0){const o=this.getWorldMatrix(),l=se.Matrix[5];o.invertToRef(l);const c=se.Vector3[8];D.TransformCoordinatesFromFloatsToRef(e,t,i,l,c);const u=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,r,n,a);return r&&D.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),u}getClosestFacetAtLocalCoordinates(e,t,i,r,n=!1,a=!0){let o=null,l=0,c=0,u=0,h=0,d=0,f=0,p=0,m=0;const g=this.getFacetLocalPositions(),_=this.getFacetLocalNormals(),y=this.getFacetsAtLocalCoordinates(e,t,i);if(!y)return null;let v=Number.MAX_VALUE,x=v,A,b,C;for(let T=0;T=0||n&&!a&&h<=0)&&(h=b.x*C.x+b.y*C.y+b.z*C.z,d=-(b.x*e+b.y*t+b.z*i-h)/(b.x*b.x+b.y*b.y+b.z*b.z),f=e+b.x*d,p=t+b.y*d,m=i+b.z*d,l=f-e,c=p-t,u=m-i,x=l*l+c*c+u*u,xe.emitter===this)}}Li.OCCLUSION_TYPE_NONE=0;Li.OCCLUSION_TYPE_OPTIMISTIC=1;Li.OCCLUSION_TYPE_STRICT=2;Li.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;Li.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;Li.CULLINGSTRATEGY_STANDARD=0;Li.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Li.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Li.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;F([l_.filter((...[s,e,t,i,r])=>!Array.isArray(s)&&!Array.isArray(e)&&!Array.isArray(t)&&!Array.isArray(i)&&!Array.isArray(r))],Li,"_ApplySkeleton",null);ve("BABYLON.AbstractMesh",Li);class e3{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){qe.Clone(()=>e,this)}serialize(){return qe.Serialize(this)}parse(e,t,i){qe.Parse(()=>this,e,t,i)}}F([X()],e3.prototype,"func",null);F([X()],e3.prototype,"funcRef",null);F([X()],e3.prototype,"funcMask",null);F([X()],e3.prototype,"opStencilFail",null);F([X()],e3.prototype,"opDepthFail",null);F([X()],e3.prototype,"opStencilDepthPass",null);F([X()],e3.prototype,"mask",null);F([X()],e3.prototype,"enabled",null);function fo(s){s.indexOf("vClipPlane")===-1&&s.push("vClipPlane"),s.indexOf("vClipPlane2")===-1&&s.push("vClipPlane2"),s.indexOf("vClipPlane3")===-1&&s.push("vClipPlane3"),s.indexOf("vClipPlane4")===-1&&s.push("vClipPlane4"),s.indexOf("vClipPlane5")===-1&&s.push("vClipPlane5"),s.indexOf("vClipPlane6")===-1&&s.push("vClipPlane6")}function t3(s,e,t){const i=!!(s.clipPlane??e.clipPlane),r=!!(s.clipPlane2??e.clipPlane2),n=!!(s.clipPlane3??e.clipPlane3),a=!!(s.clipPlane4??e.clipPlane4),o=!!(s.clipPlane5??e.clipPlane5),l=!!(s.clipPlane6??e.clipPlane6);i&&t.push("#define CLIPPLANE"),r&&t.push("#define CLIPPLANE2"),n&&t.push("#define CLIPPLANE3"),a&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function I9e(s,e,t){let i=!1;const r=!!(s.clipPlane??e.clipPlane),n=!!(s.clipPlane2??e.clipPlane2),a=!!(s.clipPlane3??e.clipPlane3),o=!!(s.clipPlane4??e.clipPlane4),l=!!(s.clipPlane5??e.clipPlane5),c=!!(s.clipPlane6??e.clipPlane6);return t.CLIPPLANE!==r&&(t.CLIPPLANE=r,i=!0),t.CLIPPLANE2!==n&&(t.CLIPPLANE2=n,i=!0),t.CLIPPLANE3!==a&&(t.CLIPPLANE3=a,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==c&&(t.CLIPPLANE6=c,i=!0),i}function Xa(s,e,t){let i=e.clipPlane??t.clipPlane;LI(s,"vClipPlane",i),i=e.clipPlane2??t.clipPlane2,LI(s,"vClipPlane2",i),i=e.clipPlane3??t.clipPlane3,LI(s,"vClipPlane3",i),i=e.clipPlane4??t.clipPlane4,LI(s,"vClipPlane4",i),i=e.clipPlane5??t.clipPlane5,LI(s,"vClipPlane5",i),i=e.clipPlane6??t.clipPlane6,LI(s,"vClipPlane6",i)}function LI(s,e,t){t&&s.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const STe=Re.Black(),ETe={NUM_MORPH_INFLUENCERS:0};function uo(s,e,t){if(!s||s.LOGARITHMICDEPTH||s.indexOf&&s.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&fe.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function ml(s,e,t,i=!1){t&&s.fogEnabled&&(!e||e.applyFog)&&s.fogMode!==0&&(t.setFloat4("vFogInfos",s.fogMode,s.fogStart,s.fogEnd,s.fogDensity),i?(s.fogColor.toLinearSpaceToRef(STe,s.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",STe)):t.setColor3("vFogColor",s.fogColor))}function rT(s,e,t){ETe.NUM_MORPH_INFLUENCERS=t,dz(s,e,ETe)}function dz(s,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&Rt.LastCreatedEngine){const r=Rt.LastCreatedEngine.getCaps().maxVertexAttribs,n=e.morphTargetManager;if(n!=null&&n.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&t.NORMAL,o=n&&n.supportsTangents&&t.TANGENT,l=n&&n.supportsUVs&&t.UV1;for(let c=0;cr&&fe.Error("Cannot add more vertex attributes for mesh "+e.name)}}function A_(s,e=!1){s.push("world0"),s.push("world1"),s.push("world2"),s.push("world3"),e&&(s.push("previousWorld0"),s.push("previousWorld1"),s.push("previousWorld2"),s.push("previousWorld3"))}function I0(s,e){const t=s.morphTargetManager;!s||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function $w(s,e){e.bindToEffect(s,"Scene")}function rn(s,e,t){e._needUVs=!0,e[t]=!0,s.optimizeUVAllocation&&s.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=s.coordinatesIndex+1,e["MAINUV"+(s.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function sn(s,e,t){const i=s.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Zw(s,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&s.push("bakedVertexAnimationSettingsInstanced")}function o2t(s,e){return e.set(s),e}function ql(s,e,t){if(!(!e||!s)&&(s.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(s.computeBonesUsingShaders=!1),s.useBones&&s.computeBonesUsingShaders&&s.skeleton)){const i=s.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const r=i.getTransformMatrixTexture(s);e.setTexture("boneSampler",r),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const r=i.getTransformMatrices(s);r&&(e.setMatrices("mBones",r),t&&s.getScene().prePassRenderer&&s.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[s.uniqueId]||(t.previousBones[s.uniqueId]=r.slice()),e.setMatrices("mPreviousBones",t.previousBones[s.uniqueId]),o2t(r,t.previousBones[s.uniqueId])))}}}function P9e(s,e,t){s.transferToEffect(e,t+"")}function fz(s,e,t,i,r,n=!0){s._bindLight(e,t,i,r,n)}function hu(s,e,t,i,r=4){const n=Math.min(e.lightSources.length,r);for(let a=0;a0&&(i.addCPUSkinningFallback(0,e),s.push("matricesIndices"),s.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(s.push("matricesIndicesExtra"),s.push("matricesWeightsExtra")))}function Ya(s,e){(e.INSTANCES||e.THIN_INSTANCES)&&A_(s,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&s.push("instanceColor")}function Zo(s,e,t=4,i=0){let r=0;for(let n=0;n0&&(r=i+n,e.addFallback(r,"LIGHT"+n)),s.SHADOWS||(s["SHADOW"+n]&&e.addFallback(i,"SHADOW"+n),s["SHADOWPCF"+n]&&e.addFallback(i,"SHADOWPCF"+n),s["SHADOWPCSS"+n]&&e.addFallback(i,"SHADOWPCSS"+n),s["SHADOWPOISSON"+n]&&e.addFallback(i,"SHADOWPOISSON"+n),s["SHADOWESM"+n]&&e.addFallback(i,"SHADOWESM"+n),s["SHADOWCLOSEESM"+n]&&e.addFallback(i,"SHADOWCLOSEESM"+n));return r++}function wJ(s,e){return e.fogEnabled&&s.applyFog&&e.fogMode!==0}function Kc(s,e,t,i,r,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=t,a.POINTSIZE=i,a.FOG=r&&wJ(s,e),a.NONUNIFORMSCALING=s.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}function du(s,e,t,i,r=4,n=!1){if(!t._areLightsDirty)return t._needNormals;let a=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(s.lightsEnabled&&!n){for(const c of e.lightSources)if(pz(s,e,c,a,t,i,o),a++,a===r)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let c=a;c0&&(a.shadowEnabled=!0,o.prepareDefines(r,i))}}t.lightmapMode!=Us.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Us.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function Hc(s,e,t,i,r,n=null,a=!1){let o=NJ(s,i);n!==!1&&(o=I9e(t,s,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function DJ(s,e){if(s.useBones&&s.computeBonesUsingShaders&&s.skeleton){e.NUM_BONE_INFLUENCERS=s.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(s.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=s.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=s.getScene().prePassRenderer;if(i&&i.enabled){const r=i.excludedSkinnedMesh.indexOf(s)===-1;e.BONES_VELOCITY_ENABLED=r}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function LJ(s,e){const t=s.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function Cge(s,e){const t=s.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function Na(s,e,t,i,r=!1,n=!0,a=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&s.isVerticesDataPresent("normal"),e._needNormals&&s.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?s.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){const o=s.useVertexColors&&s.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=s.hasVertexAlpha&&o&&n}return s.isVerticesDataPresent("instanceColor")&&(s.hasInstances||s.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&DJ(s,e),r&&LJ(s,e),a&&Cge(s,e),!0}function qw(s,e){if(s.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=s.activeCamera.outputRenderTarget!==null&&s.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function OJ(s,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,r=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=s.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!s.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||r!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function mz(s,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(s.prePassRenderer&&s.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=s.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=s.prePassRenderer.generateNormalsInWorldSpace;for(let n=0;n{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const r=t||Rt.LastCreatedScene;r&&(this._scene=r,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Me.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Ro(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new zt(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ye.OnEventObservable.notifyObservers(this,1))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const r=t.materialDefines;return r?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Ye.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ye.MATERIAL_OPAQUE||this._transparencyMode===Ye.MATERIAL_ALPHATEST}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes){for(const r of i.subMeshes)if(r.getMaterial()===this)for(const n of r._drawWrappers)n&&this._materialContext===n.materialContext&&(n._wasPreviouslyReady=!1,n._wasPreviouslyUsingInstances=null,n._forceRebindOnNextCall=e)}e&&this.markAsDirty(Ye.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(t??this.sideOrientation)===Ye.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,n,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),n}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,$w(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const r=this._scene.getEngine();this._cachedDepthWriteState=r.getDepthWrite(),r.setDepthWrite(!1)}if(this.disableColorWrite){const r=this._scene.getEngine();this._cachedColorWriteState=r.getColorWrite(),r.setColorWrite(!1)}if(this.depthFunction!==0){const r=this._scene.getEngine();this._cachedDepthFunctionState=r.getDepthFunction()||0,r.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Ye._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const r of this.pluginManager._plugins){const n=e.pluginManager.getPlugin(r.name);n&&r.copyTo(n)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,r){const n={clipPlane:!1,useInstances:!1,...i},a=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const c=a.clipPlane;if(n.clipPlane&&(a.clipPlane=new Xl(0,0,0,1)),this._storeEffectOnSubMeshes){let u=!0,h=null;if(e.subMeshes){const d=new wl(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,n.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?h=d.effect.getCompilationError():(u=!1,setTimeout(l,16)))}u&&(this.allowShaderHotSwapping=o,h&&r&&r(h),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);n.clipPlane&&(a.clipPlane=c)};l()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,n=>{r(n)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Ye._DirtyCallbackArray.length=0,e&Ye.TextureDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._TextureDirtyCallBack),e&Ye.LightDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._LightsDirtyCallBack),e&Ye.FresnelDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._FresnelDirtyCallBack),e&Ye.AttributesDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._AttributeDirtyCallBack),e&Ye.MiscDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._MiscDirtyCallBack),e&Ye.PrePassDirtyFlag&&Ye._DirtyCallbackArray.push(Ye._PrePassDirtyCallBack),Ye._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ye._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const i of t.subMeshes)i.getMaterial()===this&&i.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes){for(const r of i.subMeshes)if(r.getMaterial(!1)===this)for(const n of r._drawWrappers)!n||!n.defines||!n.defines.markAllAsDirty||this._materialContext===n.materialContext&&e(n.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Ye._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ye._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ye._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ye._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ye._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ye._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ye._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ye._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ye._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ye._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){const r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const n=this._parentContainer.materials.indexOf(this);n>-1&&this._parentContainer.materials.splice(n,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const n in this.meshMap){const a=this.meshMap[n];a&&(a.material=null,this.releaseVertexArrayObject(a,e))}else{const n=r.meshes;for(const a of n)a.material===this&&!a.sourceMesh&&(a.material=null,this.releaseVertexArrayObject(a,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=qe.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(!e.customType)e.customType="BABYLON.StandardMaterial";else if(e.customType==="BABYLON.PBRMaterial"&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return fe.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const n=Me.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}static _ParsePlugins(e,t,i,r){var n;if(e.plugins)for(const a in e.plugins){const o=e.plugins[a];let l=(n=t.pluginManager)==null?void 0:n.getPlugin(o.name);if(!l){const c=Me.Instantiate("BABYLON."+a);c&&(l=new c(t))}l==null||l.parse(o,i,r)}}}Ye.TriangleFillMode=0;Ye.WireFrameFillMode=1;Ye.PointFillMode=2;Ye.PointListDrawMode=3;Ye.LineListDrawMode=4;Ye.LineLoopDrawMode=5;Ye.LineStripDrawMode=6;Ye.TriangleStripDrawMode=7;Ye.TriangleFanDrawMode=8;Ye.ClockWiseSideOrientation=0;Ye.CounterClockWiseSideOrientation=1;Ye.TextureDirtyFlag=1;Ye.LightDirtyFlag=2;Ye.FresnelDirtyFlag=4;Ye.AttributesDirtyFlag=8;Ye.MiscDirtyFlag=16;Ye.PrePassDirtyFlag=32;Ye.AllDirtyFlag=63;Ye.MATERIAL_OPAQUE=0;Ye.MATERIAL_ALPHATEST=1;Ye.MATERIAL_ALPHABLEND=2;Ye.MATERIAL_ALPHATESTANDBLEND=3;Ye.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;Ye.MATERIAL_NORMALBLENDMETHOD_RNM=1;Ye.OnEventObservable=new Ae;Ye._AllDirtyCallBack=s=>s.markAllAsDirty();Ye._ImageProcessingDirtyCallBack=s=>s.markAsImageProcessingDirty();Ye._TextureDirtyCallBack=s=>s.markAsTexturesDirty();Ye._FresnelDirtyCallBack=s=>s.markAsFresnelDirty();Ye._MiscDirtyCallBack=s=>s.markAsMiscDirty();Ye._PrePassDirtyCallBack=s=>s.markAsPrePassDirty();Ye._LightsDirtyCallBack=s=>s.markAsLightDirty();Ye._AttributeDirtyCallBack=s=>s.markAsAttributesDirty();Ye._FresnelAndMiscDirtyCallBack=s=>{Ye._FresnelDirtyCallBack(s),Ye._MiscDirtyCallBack(s)};Ye._TextureAndMiscDirtyCallBack=s=>{Ye._TextureDirtyCallBack(s),Ye._MiscDirtyCallBack(s)};Ye._DirtyCallbackArray=[];Ye._RunDirtyCallBacks=s=>{for(const e of Ye._DirtyCallbackArray)e(s)};F([X()],Ye.prototype,"id",void 0);F([X()],Ye.prototype,"uniqueId",void 0);F([X()],Ye.prototype,"name",void 0);F([X()],Ye.prototype,"metadata",void 0);F([X()],Ye.prototype,"checkReadyOnEveryCall",void 0);F([X()],Ye.prototype,"checkReadyOnlyOnce",void 0);F([X()],Ye.prototype,"state",void 0);F([X("alpha")],Ye.prototype,"_alpha",void 0);F([X("backFaceCulling")],Ye.prototype,"_backFaceCulling",void 0);F([X("cullBackFaces")],Ye.prototype,"_cullBackFaces",void 0);F([X()],Ye.prototype,"sideOrientation",void 0);F([X("alphaMode")],Ye.prototype,"_alphaMode",void 0);F([X()],Ye.prototype,"_needDepthPrePass",void 0);F([X()],Ye.prototype,"disableDepthWrite",void 0);F([X()],Ye.prototype,"disableColorWrite",void 0);F([X()],Ye.prototype,"forceDepthWrite",void 0);F([X()],Ye.prototype,"depthFunction",void 0);F([X()],Ye.prototype,"separateCullingPass",void 0);F([X("fogEnabled")],Ye.prototype,"_fogEnabled",void 0);F([X()],Ye.prototype,"pointSize",void 0);F([X()],Ye.prototype,"zOffset",void 0);F([X()],Ye.prototype,"zOffsetUnits",void 0);F([X()],Ye.prototype,"pointsCloud",null);F([X()],Ye.prototype,"fillMode",null);F([X()],Ye.prototype,"useLogarithmicDepth",null);F([X()],Ye.prototype,"transparencyMode",null);class Zd extends Ye{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...r)=>{const n=t.apply(e,r);return this._markAllSubMeshesAsTexturesDirty(),n};const i=e.splice;e.splice=(r,n)=>{const a=i.apply(e,[r,n]);return this._markAllSubMeshesAsTexturesDirty(),a}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(n,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Zd(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Br&&Br.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(r=>i.subMaterials.push(t.getLastMaterialById(r))),i}}ve("BABYLON.MultiMaterial",Zd);class w9e{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Sge{}class l2t{constructor(){this.visibleInstances={},this.batchCache=new Due,this.batchCacheReplacementModeInFrozenMode=new Due,this.instancesBufferSize=32*16*4}}class Due{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class c2t{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class u2t{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class Ee extends Li{static _GetDefaultSideOrientation(e){return e||Ee.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData($.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData($.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new Ae),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Ae),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Ae),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Ae),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Ae),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0){const r=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),Nl.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,r.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const n=e._ranges;for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&n[a]&&this.createAnimationRange(a,n[a].from,n[a].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,Br&&Br.HasTags(e)&&Br.AddTagsTo(this,Br.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const n=e.getDescendants(!0);for(let a=0;a{o&&c&&(this._uniformBuffer?this.transferToEffect(l):c.bindOnlyWorldMatrix(l))},r&&this._copySource(r,n,a),i!==null&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=o=>{o.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new Ae(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const r=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(const n of this.getChildTransformNodes(!0))n.getClassName()==="InstancedMesh"&&r.getClassName()==="Mesh"&&n.sourceMesh===this?n.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):n.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return fe.Warn("You cannot use a mesh as LOD level twice"),this;const i=new w9e(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const a=this.material||r.defaultMaterial;if(a){if(a._storeEffectOnSubMeshes)for(const f of this.subMeshes){const p=f.getMaterial();if(p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,f,n))return!1}else if(!p.isReady(this,n))return!1}}else if(!a.isReady(this,n))return!1}const o=i.currentRenderPassId;for(const f of this.lightSources){const p=f.getShadowGenerators();if(!p)continue;const m=p.values();for(let g=m.next();g.done!==!0;g=m.next()){const _=g.value;if(_&&(!((l=_.getShadowMap())!=null&&l.renderList)||(c=_.getShadowMap())!=null&&c.renderList&&((h=(u=_.getShadowMap())==null?void 0:u.renderList)==null?void 0:h.indexOf(this))!==-1)){const v=_.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let x=0;x0){const i=this.getIndices();if(!i)return null;const r=i.length;let n=!1;if(e)n=!0;else for(const a of this.subMeshes){if(a.indexStart+a.indexCount>r){n=!0;break}if(a.verticesStart+a.verticesCount>t){n=!0;break}}if(!n)return this.subMeshes[0]}return this.releaseSubMeshes(),new wl(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,r=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let n=0;n=t);n++)wl.CreateFromIndices(0,r,n===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{const n=new at;n.set(t,e);const a=this.getScene();new So(So.RandomId(),a,n,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);!i||i.isUpdatable()===t||this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=So.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData($.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData($.PositionKind,i,!1,!1),t){const r=this.getIndices(),n=this.getVerticesData($.NormalKind);if(!n)return this;at.ComputeNormals(i,r,n),this.updateVerticesData($.NormalKind,n,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;const e=this._geometry,t=this._geometry.copy(So.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let r=this._geometry;r||(r=new So(So.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const r=new at;r.indices=e;const n=this.getScene();new So(So.RandomId(),n,r,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;const n=this.getScene().getEngine();let a;if(this._unIndexed)a=null;else switch(this._getRenderingFillMode(i)){case Ye.PointFillMode:a=null;break;case Ye.WireFrameFillMode:a=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case Ye.TriangleFillMode:a=this._geometry.getIndexBuffer();break}return this._bindDirect(t,a,r)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(e,t):this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),this):this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const n=this.getScene().getEngine();return this._unIndexed||t==Ye.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ye.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):n.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),r=i._isInIntermediateRendering(),n=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),c=r?o.intermediateDefaultRenderId:o.defaultRenderId;a.visibleInstances[e]=o[l],!a.visibleInstances[e]&&c&&(a.visibleInstances[e]=o[c])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&a.visibleInstances[e]!==null&&a.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,i,r,n){var y;const a=i.visibleInstances[e._id],o=a?a.length:0,l=this._instanceDataStorage,c=l.instancesBufferSize;let u=l.instancesBuffer,h=l.instancesPreviousBuffer;const f=(o+1)*16*4;for(;l.instancesBufferSizeA._distanceToCamera>b._distanceToCamera?-1:A._distanceToCamera1&&r.activeCamera===r.activeCameras[0]||n<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const o=this._getInstancesRenderList(e._id,!!i);if(o.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const l=r.getEngine();let c=0,u=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(c=r.activeCamera.maxZ,u=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),d=o.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,f=this._instanceDataStorage,p=e.getMaterial();if(!p)return u&&(u.maxZ=c,r.updateTransformMatrix(!0)),this;if(!f.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,d))return u&&(u.maxZ=c,r.updateTransformMatrix(!0)),this}else if(!p.isReady(this,d))return u&&(u.maxZ=c,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!((T=e._drawWrapper)!=null&&T._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return u&&(u.maxZ=c,r.updateTransformMatrix(!0)),this;t&&l.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let m;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?m=e._drawWrapper:m=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const g=(m==null?void 0:m.effect)??null;for(const w of r._beforeRenderingMeshStage)w.action(this,e,o,g);if(!m||!g)return u&&(u.maxZ=c,r.updateTransformMatrix(!0)),this;const _=i||this;let y;if(!f.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this._internalMeshDataInfo._effectiveMaterial.sideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const w=_._getWorldMatrixDeterminant();y=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),w<0&&(y=y===Ye.ClockWiseSideOrientation?Ye.CounterClockWiseSideOrientation:Ye.ClockWiseSideOrientation),f.sideOrientation=y}else y=f.sideOrientation;const v=this._internalMeshDataInfo._effectiveMaterial._preBind(m,y);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&l.setDepthWrite(!0);const x=this._internalMeshDataInfo._effectiveMaterial,A=x.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,g,A,!1);const b=_.getWorldMatrix();x._storeEffectOnSubMeshes?x.bindForSubMesh(b,this,e):x.bind(b,this),!x.backFaceCulling&&x.separateCullingPass&&(l.setState(!0,x.zOffset,!1,!v,x.cullBackFaces,x.stencil,x.zOffsetUnits),this._processRendering(this,e,g,A,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),l.setState(!0,x.zOffset,!1,v,x.cullBackFaces,x.stencil,x.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,g,A,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const w of r._afterRenderingMeshStage)w.action(this,e,o,g);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),u&&(u.maxZ=c,r.updateTransformMatrix(!0)),r.performancePriority===2&&!f.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent($.MatricesWeightsKind)&&(this.isVerticesDataPresent($.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData($.MatricesWeightsKind),t=e.length;for(let i=0;i_&&r++,A!==0&&v++,y+=A,_=A}if(c[v]++,v>a&&(a=v),y===0)n++;else{const x=1/y;let A=0;for(let b=0;bu&&o++}}const h=this.skeleton.bones.length,d=this.getVerticesData($.MatricesIndicesKind),f=this.getVerticesData($.MatricesIndicesExtraKind);let p=0;for(let g=0;g=h||y<0)&&p++}const m="Number of Weights = "+i/4+` Maximum influences = `+a+` Missing Weights = `+n+` Not Sorted = `+r+` Not Normalized = `+o+` WeightCounts = [`+c+`] Number of bones = `+h+` Bad Bone Indices = `+p;return{skinned:!0,valid:n===0&&o===0&&p===0,report:m}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return Me.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(r=>{r.refreshBoundingInfo(),r._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent($.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData($.PositionKind);const r=D.Zero();let n;for(n=0;n{const d=h.width,f=h.height,m=this.getEngine().createCanvas(d,f).getContext("2d");m.drawImage(h,0,0);const g=m.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(g,d,f,t,i,n,a,o),r&&r(this)};return Me.LoadImage(e,u,l||(()=>{}),c.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,n,a,o,l=!1){if(!this.isVerticesDataPresent($.PositionKind)||!this.isVerticesDataPresent($.NormalKind)||!this.isVerticesDataPresent($.UVKind))return fe.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const c=this.getVerticesData($.PositionKind,!0,!0),u=this.getVerticesData($.NormalKind),h=this.getVerticesData($.UVKind);let d=D.Zero();const f=D.Zero(),p=we.Zero();a=a||we.Zero(),o=o||new we(1,1);for(let m=0;m{var c;return!((c=this.getVertexBuffer(l))!=null&&c.getIsInstanced())}),i=this.getIndices(),r={},n=(l,c)=>{const u=new Float32Array(i.length*c);let h=0;for(let d=0;d{const o=r.length-1-a,l=r[o];for(let c=0;c{for(let o=0;o-1&&(r.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let n=0;n4,c=l?this.getVerticesData($.MatricesIndicesExtraKind):null,u=l?this.getVerticesData($.MatricesWeightsExtraKind):null,h=e.getTransformMatrices(this),d=D.Zero(),f=new he,p=new he;let m=0,g;for(let _=0;_0&&(he.FromFloat32ArrayToRefScaled(h,Math.floor(a[m+g]*16),y,p),f.addToSelf(p));if(l)for(g=0;g<4;g++)y=u[m+g],y>0&&(he.FromFloat32ArrayToRefScaled(h,Math.floor(c[m+g]*16),y,p),f.addToSelf(p));D.TransformCoordinatesFromFloatsToRef(i._sourcePositions[_],i._sourcePositions[_+1],i._sourcePositions[_+2],f,d),d.toArray(r,_),t&&(D.TransformNormalFromFloatsToRef(i._sourceNormals[_],i._sourceNormals[_+1],i._sourceNormals[_+2],f,d),d.toArray(n,_)),f.reset()}return this.updateVerticesData($.PositionKind,r),t&&this.updateVerticesData($.NormalKind,n),this}static MinMax(e){let t=null,i=null;return e.forEach(function(r){const a=r.getBoundingInfo().boundingBox;!t||!i?(t=a.minimumWorld,i=a.maximumWorld):(t.minimizeInPlace(a.minimumWorld),i.maximizeInPlace(a.maximumWorld))}),!t||!i?{min:D.Zero(),max:D.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?Ee.MinMax(e):e;return D.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,n,a){return RJ(Ee._MergeMeshesCoroutine(e,t,i,r,n,a,!1))}static MergeMeshesAsync(e,t=!0,i,r,n,a){return IJ(Ee._MergeMeshesCoroutine(e,t,i,r,n,a,!0),S9e())}static*_MergeMeshesCoroutine(e,t=!0,i,r,n,a,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let C=0;for(l=0;l=65536)return fe.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(n=!1);const c=new Array,u=new Array,h=new Array,d=e[0].sideOrientation;for(l=0;l{const T=C.computeWorldMatrix(!0);return{vertexData:at.ExtractFromMesh(C,!1,!1),transform:T}},{vertexData:m,transform:g}=p(f);o&&(yield);const _=new Array(e.length-1);for(let C=1;C{throw vi("GroundMesh")};Ee._GoldbergMeshParser=(s,e)=>{throw vi("GoldbergMesh")};Ee._LinesMeshParser=(s,e)=>{throw vi("LinesMesh")};Ee._GreasedLineMeshParser=(s,e)=>{throw vi("GreasedLineMesh")};Ee._GreasedLineRibbonMeshParser=(s,e)=>{throw vi("GreasedLineRibbonMesh")};Ee._TrailMeshParser=(s,e)=>{throw vi("TrailMesh")};ve("BABYLON.Mesh",Ee);Ee._instancedMeshFactory=(s,e)=>{const t=new C0(s,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class C0 extends Li{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&Me.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&Me.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&Me.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&Me.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||fe.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};const r=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,$.PositionKind),r),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||fe.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==_t.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new he);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,se.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(se.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{const i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&!(this.includeOnlyWithLayerMask&e.layerMask)||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(const i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=Zi.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const r=qe.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){const e=qe.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach(t=>{e.excludedMeshesIds.push(t.id)})),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(t=>{e.includedOnlyMeshesIds.push(t.id)})),qe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const r=ns.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){const i=Zi.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const r=qe.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(r.falloffType=e.falloffType),e.lightmapMode!==void 0&&(r.lightmapMode=e.lightmapMode),e.animations){for(let n=0;n{const n=t.apply(e,r);for(const a of r)a._resyncLightSource(this);return n};const i=e.splice;e.splice=(r,n)=>{const a=i.apply(e,[r,n]);for(const o of a)o._resyncLightSource(this);return a};for(const r of e)r._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...r)=>{const n=t.apply(e,r);return this._resyncMeshes(),n};const i=e.splice;e.splice=(r,n)=>{const a=i.apply(e,[r,n]);return this._resyncMeshes(),a},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Zi.INTENSITYMODE_AUTOMATIC&&(t===Zi.LIGHTTYPEID_DIRECTIONALLIGHT?i=Zi.INTENSITYMODE_ILLUMINANCE:i=Zi.INTENSITYMODE_LUMINOUSINTENSITY),t){case Zi.LIGHTTYPEID_POINTLIGHT:case Zi.LIGHTTYPEID_SPOTLIGHT:switch(i){case Zi.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Zi.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Zi.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Zi.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Zi.INTENSITYMODE_ILLUMINANCE:e=1;break;case Zi.INTENSITYMODE_LUMINANCE:{let r=this.radius;r=Math.max(r,.001),e=2*Math.PI*(1-Math.cos(r));break}}break;case Zi.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Zi.FALLOFF_DEFAULT=Us.FALLOFF_DEFAULT;Zi.FALLOFF_PHYSICAL=Us.FALLOFF_PHYSICAL;Zi.FALLOFF_GLTF=Us.FALLOFF_GLTF;Zi.FALLOFF_STANDARD=Us.FALLOFF_STANDARD;Zi.LIGHTMAP_DEFAULT=Us.LIGHTMAP_DEFAULT;Zi.LIGHTMAP_SPECULAR=Us.LIGHTMAP_SPECULAR;Zi.LIGHTMAP_SHADOWSONLY=Us.LIGHTMAP_SHADOWSONLY;Zi.INTENSITYMODE_AUTOMATIC=Us.INTENSITYMODE_AUTOMATIC;Zi.INTENSITYMODE_LUMINOUSPOWER=Us.INTENSITYMODE_LUMINOUSPOWER;Zi.INTENSITYMODE_LUMINOUSINTENSITY=Us.INTENSITYMODE_LUMINOUSINTENSITY;Zi.INTENSITYMODE_ILLUMINANCE=Us.INTENSITYMODE_ILLUMINANCE;Zi.INTENSITYMODE_LUMINANCE=Us.INTENSITYMODE_LUMINANCE;Zi.LIGHTTYPEID_POINTLIGHT=Us.LIGHTTYPEID_POINTLIGHT;Zi.LIGHTTYPEID_DIRECTIONALLIGHT=Us.LIGHTTYPEID_DIRECTIONALLIGHT;Zi.LIGHTTYPEID_SPOTLIGHT=Us.LIGHTTYPEID_SPOTLIGHT;Zi.LIGHTTYPEID_HEMISPHERICLIGHT=Us.LIGHTTYPEID_HEMISPHERICLIGHT;F([br()],Zi.prototype,"diffuse",void 0);F([br()],Zi.prototype,"specular",void 0);F([X()],Zi.prototype,"falloffType",void 0);F([X()],Zi.prototype,"intensity",void 0);F([X()],Zi.prototype,"range",null);F([X()],Zi.prototype,"intensityMode",null);F([X()],Zi.prototype,"radius",null);F([X()],Zi.prototype,"_renderPriority",void 0);F([Fe("_reorderLightsInScene")],Zi.prototype,"renderPriority",void 0);F([X("shadowEnabled")],Zi.prototype,"_shadowEnabled",void 0);F([X("excludeWithLayerMask")],Zi.prototype,"_excludeWithLayerMask",void 0);F([X("includeOnlyWithLayerMask")],Zi.prototype,"_includeOnlyWithLayerMask",void 0);F([X("lightmapMode")],Zi.prototype,"_lightmapMode",void 0);class D9e extends Oa{}class L9e{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach(e=>{e.dispose()}),this.rootNodes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0}}class _z extends Oa{constructor(e){super(),this._wasAddedToScene=!1,e=e||Rt.LastCreatedScene,e&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(const t of this.geometries)t._rebuild();for(const t of this.meshes)t._rebuild();for(const t of this.particleSystems)t.rebuild();for(const t of this.textures)t._rebuild()}))}_topologicalSort(e){const t=new Map;for(const o of e)t.set(o.uniqueId,o);const i={dependsOn:new Map,dependedBy:new Map};for(const o of e){const l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(const o of e){const l=o.uniqueId,c=i.dependsOn.get(l);if(o instanceof C0){const h=o.sourceMesh;t.has(h.uniqueId)&&(c.add(h.uniqueId),i.dependedBy.get(h.uniqueId).add(l))}const u=i.dependedBy.get(l);for(const h of o.getDescendants()){const d=h.uniqueId;t.has(d)&&(u.add(d),i.dependsOn.get(d).add(l))}}const r=[],n=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(n.push(o),t.delete(l))}const a=n;for(;a.length>0;){const o=a.shift();r.push(o);const l=i.dependedBy.get(o.uniqueId);for(const c of Array.from(l.values())){const u=i.dependsOn.get(c);u.delete(o.uniqueId),u.size===0&&t.get(c)&&(a.push(t.get(c)),t.delete(c))}}return t.size>0&&(fe.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>fe.Error(o.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const n of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,n,r)}}_isNodeInContainer(e){return e instanceof Li&&this.meshes.indexOf(e)!==-1||e instanceof _t&&this.transformNodes.indexOf(e)!==-1||e instanceof Zi&&this.lights.indexOf(e)!==-1||e instanceof Nt&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return fe.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return fe.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return fe.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return fe.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Me.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const r={},n={},a=new L9e,o=[],l=[],c={doNotInstantiate:!0,...i},u=(m,g)=>{if(r[m.uniqueId]=g.uniqueId,n[g.uniqueId]=g,e&&(g.name=e(m.name)),g instanceof Ee){const _=g;if(_.morphTargetManager){const y=m.morphTargetManager;_.morphTargetManager=y.clone();for(let v=0;v{if(u(m,g),m.parent){const _=r[m.parent.uniqueId],y=n[_];y?g.parent=y:g.parent=m.parent}if(g.position&&m.position&&g.position.copyFrom(m.position),g.rotationQuaternion&&m.rotationQuaternion&&g.rotationQuaternion.copyFrom(m.rotationQuaternion),g.rotation&&m.rotation&&g.rotation.copyFrom(m.rotation),g.scaling&&m.scaling&&g.scaling.copyFrom(m.scaling),g.material){const _=g;if(_.material)if(t){const y=m.material;if(l.indexOf(y)===-1){let v=y.clone(e?e(y.name):"Clone of "+y.name);if(l.push(y),r[y.uniqueId]=v.uniqueId,n[v.uniqueId]=v,y.getClassName()==="MultiMaterial"){const x=y;for(const A of x.subMaterials)A&&(v=A.clone(e?e(A.name):"Clone of "+A.name),l.push(A),r[A.uniqueId]=v.uniqueId,n[v.uniqueId]=v);x.subMaterials=x.subMaterials.map(A=>A&&n[r[A.uniqueId]])}}_.getClassName()!=="InstancedMesh"&&(_.material=n[r[y.uniqueId]])}else _.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(_.material)===-1&&this.scene.addMultiMaterial(_.material):this.scene.materials.indexOf(_.material)===-1&&this.scene.addMaterial(_.material)}g.parent===null&&a.rootNodes.push(g)};return f.forEach(m=>{if(m.getClassName()==="InstancedMesh"){const g=m,_=g.sourceMesh,y=r[_.uniqueId],x=(typeof y=="number"?n[y]:_).createInstance(g.name);p(g,x)}else{let g=!0;m.getClassName()==="TransformNode"||m.getClassName()==="Node"||m.skeleton||!m.getTotalVertices||m.getTotalVertices()===0?g=!1:c.doNotInstantiate&&(typeof c.doNotInstantiate=="function"?g=!c.doNotInstantiate(m):g=!c.doNotInstantiate);const _=g?m.createInstance(`instance of ${m.name}`):m.clone(`Clone of ${m.name}`,null,!0);if(!_)throw new Error(`Could not clone or instantiate node on Asset Container ${m.name}`);p(m,_)}}),this.skeletons.forEach(m=>{if(c.predicate&&!c.predicate(m))return;const g=m.clone(e?e(m.name):"Clone of "+m.name);for(const _ of this.meshes)if(_.skeleton===m&&!_.isAnInstance){const y=n[r[_.uniqueId]];if(!y||y.isAnInstance||(y.skeleton=g,o.indexOf(g)!==-1))continue;o.push(g);for(const v of g.bones)v._linkedTransformNode&&(v._linkedTransformNode=n[r[v._linkedTransformNode.uniqueId]])}a.skeletons.push(g)}),this.animationGroups.forEach(m=>{if(c.predicate&&!c.predicate(m))return;const g=m.clone(e?e(m.name):"Clone of "+m.name,_=>n[r[_.uniqueId]]||_);a.animationGroups.push(g)}),a}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Me.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach(i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(i=>{e&&!e(i)||this.scene.addSkeleton(i)}),this.animations.forEach(i=>{e&&!e(i)||this.scene.addAnimation(i)}),this.animationGroups.forEach(i=>{e&&!e(i)||this.scene.addAnimationGroup(i)}),this.multiMaterials.forEach(i=>{e&&!e(i)||this.scene.addMultiMaterial(i)}),this.materials.forEach(i=>{e&&!e(i)||this.scene.addMaterial(i)}),this.morphTargetManagers.forEach(i=>{e&&!e(i)||this.scene.addMorphTargetManager(i)}),this.geometries.forEach(i=>{e&&!e(i)||this.scene.addGeometry(i)}),this.transformNodes.forEach(i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(i=>{e&&!e(i)||this.scene.addActionManager(i)}),this.textures.forEach(i=>{e&&!e(i)||this.scene.addTexture(i)}),this.reflectionProbes.forEach(i=>{e&&!e(i)||this.scene.addReflectionProbe(i)});for(const i of t)i.parent&&this.scene.getNodes().indexOf(i.parent)===-1&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Me.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{e&&!e(t)||this.scene.removeCamera(t)}),this.lights.forEach(t=>{e&&!e(t)||this.scene.removeLight(t)}),this.meshes.forEach(t=>{e&&!e(t)||this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{e&&!e(t)||this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{e&&!e(t)||this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{e&&!e(t)||this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{e&&!e(t)||this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{e&&!e(t)||this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{e&&!e(t)||this.scene.removeActionManager(t)}),this.textures.forEach(t=>{e&&!e(t)||this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)})}dispose(){this.cameras.slice(0).forEach(e=>{e.dispose()}),this.cameras.length=0,this.lights.slice(0).forEach(e=>{e.dispose()}),this.lights.length=0,this.meshes.slice(0).forEach(e=>{e.dispose()}),this.meshes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach(e=>{e.dispose()}),this.multiMaterials.length=0,this.materials.slice(0).forEach(e=>{e.dispose()}),this.materials.length=0,this.geometries.slice(0).forEach(e=>{e.dispose()}),this.geometries.length=0,this.transformNodes.slice(0).forEach(e=>{e.dispose()}),this.transformNodes.length=0,this.actionManagers.slice(0).forEach(e=>{e.dispose()}),this.actionManagers.length=0,this.textures.slice(0).forEach(e=>{e.dispose()}),this.textures.length=0,this.reflectionProbes.slice(0).forEach(e=>{e.dispose()}),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach(e=>{e.dispose()}),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(const r of e){let n=!0;if(i){for(const a of i)if(r===a){n=!1;break}}n&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new D9e);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Ee("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=Rt.LastCreatedScene,t,i=null){if(!e)return fe.Error("No scene available to merge animations to"),[];const r=i||(o=>{let l=null;const c=o.animations.length?o.animations[0].targetProperty:"",u=o.name.split(".").join("").split("_primitive")[0];switch(c){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(u);break;case"influence":l=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(u);break;default:l=e.getNodeByName(o.name)||e.getNodeByName(u)}return l});this.getNodes().forEach(o=>{const l=r(o);if(l!==null){for(const c of o.animations){const u=l.animations.filter(h=>h.targetProperty===c.targetProperty);for(const h of u){const d=l.animations.indexOf(h,0);d>-1&&l.animations.splice(d,1)}}l.animations=l.animations.concat(o.animations)}});const a=[];return this.animationGroups.slice().forEach(o=>{a.push(o.clone(o.name,r)),o.animatables.forEach(l=>{l.stop()})}),t.forEach(o=>{const l=r(o.target);l&&(e.beginAnimation(l,o.fromFrame,o.toFrame,o.loopAnimation,o.speedRatio,o.onAnimationEnd?o.onAnimationEnd:void 0,void 0,!0,void 0,o.onAnimationLoop?o.onAnimationLoop:void 0),e.stopAnimation(o.target))}),a}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.lights.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.cameras.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const r=t.pop();if(r instanceof Ee?(r.geometry&&this.geometries.indexOf(r.geometry)===-1&&this.geometries.push(r.geometry),this.meshes.push(r)):r instanceof _t?this.transformNodes.push(r):r instanceof Zi?this.lights.push(r):r instanceof Nt&&this.cameras.push(r),r instanceof Li){if(r.material&&this.materials.indexOf(r.material)===-1){this.materials.push(r.material);for(const n of r.material.getActiveTextures())this.textures.indexOf(n)===-1&&this.textures.push(n)}r.skeleton&&this.skeletons.indexOf(r.skeleton)===-1&&this.skeletons.push(r.skeleton),r.morphTargetManager&&this.morphTargetManagers.indexOf(r.morphTargetManager)===-1&&this.morphTargetManagers.push(r.morphTargetManager)}for(const n of r.getChildren())i.has(n)||t.push(n);i.add(r)}this.populateRootNodes()}}class h2t{constructor(e){if(this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},e=e||Rt.LastCreatedScene,!!e){if(this._scene=e,!Ge.audioEngine){Me.Warn("No audio engine initialized, failed to create an audio analyser");return}this._audioEngine=Ge.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))}}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tnew O9e(s,e,t);class O9e{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new Ae,this.onAudioLockedObservable=new Ae,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!To())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if(((e=this._audioContext)==null?void 0:e.state)==="running"){this._hideMuteButton(),this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this));return}this._tryToRun?(t=this._audioContext)==null||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContextOnStateChange(){var e;(e=this._audioContext)==null||e.addEventListener("statechange",()=>{var t;this.unlocked&&((t=this._audioContext)==null?void 0:t.state)!=="running"&&this._resumeAudioContext()},{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){var e;return(e=this._audioContext)!=null&&e.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,this._audioContext.state==="running"&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,fe.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)}).catch(()=>{this._tryToRun=!1,this.unlocked=!1}))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Wd{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((e=Ge.audioEngine)!=null&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:Ge.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+t}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,n){var a;if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new Ae,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=D.Zero(),this._localDirection=new D(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||Rt.LastCreatedScene,!!i)if(this._scene=i,Wd._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(o,l,c,u,h)=>l0&&(c=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":l.push(t);case"Array":l.length===0&&(l=t);for(let u=0;u{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(h,d=>{this._soundLoaded(d)},void 0,!0,!0,d=>{d&&fe.Error("XHR "+d.status+" error on: "+h+"."),fe.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:o=!1;break}o?c||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):fe.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{fe.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Ge.audioEngine&&!Ge.audioEngine.WarnedWebAudioUnsupported&&(fe.Error("Web Audio is not supported by your browser."),Ge.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(e=Ge.audioEngine)!=null&&e.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(t=Ge.audioEngine)!=null&&t.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(t=Ge.audioEngine)!=null&&t.audioContext&&Ge.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{fe.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;(t=Ge.audioEngine)!=null&&t.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),this._offset!==void 0&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),this._length!==void 0&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(this._offset|0)+this._length))))}_createSpatialParameters(){var e;(e=Ge.audioEngine)!=null&&e.canUseWebAudio&&Ge.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Ge.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,(e=this._soundPanner)==null||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(e=Ge.audioEngine)!=null&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(t=Ge.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const c=()=>{var u,h;if((u=Ge.audioEngine)!=null&&u.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,p;(f=Ge.audioEngine)==null||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(p=Ge.audioEngine)==null?void 0:p.onAudioUnlockedObservable.addOnce(()=>{c()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(h=Ge.audioEngine)==null?void 0:h.onAudioUnlockedObservable.addOnce(()=>{c()}))};c()}}else{const c=()=>{var u,h,d;if((u=Ge.audioEngine)!=null&&u.audioContext){if(i=i||this._length,t!==void 0&&this._setOffset(t),this._soundSource){const f=this._soundSource;f.onended=()=>{f.disconnect()}}if(this._soundSource=(h=Ge.audioEngine)==null?void 0:h.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,t!==void 0&&(this._soundSource.loopStart=t),i!==void 0&&(this._soundSource.loopEnd=(t|0)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},l=e?((d=Ge.audioEngine)==null?void 0:d.audioContext.currentTime)+e:Ge.audioEngine.audioContext.currentTime;const f=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(l,f,this.loop?void 0:i)}}};((o=Ge.audioEngine)==null?void 0:o.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var u;((u=Ge.audioEngine)==null?void 0:u.audioContext.state)==="suspended"?(Ge.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ge.audioEngine.onAudioUnlockedObservable.addOnce(()=>{c()}))):c()},500):c()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){fe.Error("Error while trying to play audio: "+this.name+", "+l.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((t=Ge.audioEngine)!=null&&t.audioContext&&this._soundSource){const i=e?Ge.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(i)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(e=Ge.audioEngine)!=null&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Ge.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(i=Ge.audioEngine)!=null&&i.canUseWebAudio&&this._soundGain&&(t&&Ge.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Ge.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Ge.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Ge.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=t=>this._onRegisterAfterWorldMatrixUpdate(t),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){var t;if(!e.getBoundingInfo)this.setPosition(e.absolutePosition);else{const r=e.getBoundingInfo();this.setPosition(r.boundingSphere.centerWorld)}(t=Ge.audioEngine)!=null&&t.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Wd(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,r){const n=e.name;let a;e.url?a=i+e.url:a=i+n;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let l;if(!r)l=new Wd(n,a,t,()=>{t.removePendingData(l)},o),t.addPendingData(l);else{const c=()=>{r._isReadyToPlay?(l._audioBuffer=r.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(c,300)};l=new Wd(n,new ArrayBuffer(0),t,null,o),c()}if(e.position){const c=D.FromArray(e.position);l.setPosition(c)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const c=D.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(c)}if(e.connectedMeshId){const c=t.getMeshById(e.connectedMeshId);c&&l.attachToMesh(c)}return e.metadata&&(l.metadata=e.metadata),l}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&((e=Ge.audioEngine)==null||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Wd._SceneComponentInitialization=s=>{throw vi("AudioSceneComponent")};ve("BABYLON.Sound",Wd);class N9e{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||Rt.LastCreatedScene,e&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){var e;(e=Ge.audioEngine)!=null&&e.canUseWebAudio&&Ge.audioEngine.audioContext&&(this._outputAudioNode=Ge.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Ge.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(Ge.audioEngine&&Ge.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(t=Ge.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId!==void 0&&(e.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);t!==-1&&this.soundCollection.splice(t,1)}setVolume(e){var t;(t=Ge.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if((e=Ge.audioEngine)!=null&&e.canUseWebAudio)for(let t=0;t{var a;let r=[],n;if(t.sounds=t.sounds||[],s.sounds!==void 0&&s.sounds!==null)for(let o=0,l=s.sounds.length;o{t.play(),t.autoplay=!0,this.scene.mainSoundTrack.addSound(t)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(i=>{i.stop(),i.autoplay=!1,this.scene.mainSoundTrack.removeSound(i),t&&i.dispose()})}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){const a=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(a.x||0,a.y||0,a.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const a=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(a.x||0,a.y||0,a.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),D.TransformNormalToRef(xh._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),!isNaN(this._cameraDirectionTemp.x)&&!isNaN(this._cameraDirectionTemp.y)&&!isNaN(this._cameraDirectionTemp.z)&&(this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0)))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);let n;for(n=0;n{let e=s._getComponent(ot.NAME_AUDIO);e||(e=new xh(s),s._addComponent(e))};class F9e{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let r=0;for(const a of i)r+=a;const n=r>0?1/r:0;for(let a=0;a{this._onended()})}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee,this)}serialize(){return qe.Serialize(this)}parse(e,t,i){qe.Parse(()=>this,e,t,i)}}F([ii(),Fe("_markSubMeshesAsAttributesDirty")],sT.prototype,"texture",void 0);F([X(),Fe("_markSubMeshesAsAttributesDirty")],sT.prototype,"isEnabled",void 0);F([X()],sT.prototype,"animationParameters",void 0);F([X()],sT.prototype,"time",void 0);class lv{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e.shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=iu.Zero(),this._cachedBaseSize=iu.Zero(),this._initialSamplingMode=2,this._texture=lv._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}function cZ(s,e,t=!1,i){switch(s){case 3:{const n=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&n.set(new Int8Array(i)),n}case 0:{const n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&n.set(new Uint8Array(i)),n}case 4:{const n=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&n.set(new Int16Array(i)),n}case 5:case 8:case 9:case 10:case 2:{const n=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&n.set(new Uint16Array(i)),n}case 6:{const n=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&n.set(new Int32Array(i)),n}case 7:case 11:case 12:case 13:case 14:case 15:{const n=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&n.set(new Uint32Array(i)),n}case 1:{const n=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&n.set(new Float32Array(i)),n}}const r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}bi.prototype._readTexturePixelsSync=function(s,e,t,i=-1,r=0,n=null,a=!0,o=!1,l=0,c=0){var d,f;const u=this._gl;if(!u)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const p=u.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}u.bindFramebuffer(u.FRAMEBUFFER,this._dummyFramebuffer),i>-1?u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_CUBE_MAP_POSITIVE_X+i,(d=s._hardwareTexture)==null?void 0:d.underlyingResource,r):u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,(f=s._hardwareTexture)==null?void 0:f.underlyingResource,r);let h=s.type!==void 0?this._getWebGLTextureType(s.type):u.UNSIGNED_BYTE;if(o)n||(n=cZ(s.type,4*e*t));else switch(h){case u.UNSIGNED_BYTE:n||(n=new Uint8Array(4*e*t)),h=u.UNSIGNED_BYTE;break;default:n||(n=new Float32Array(4*e*t)),h=u.FLOAT;break}return a&&this.flushFramebuffer(),u.readPixels(l,c,e,t,u.RGBA,h,n),u.bindFramebuffer(u.FRAMEBUFFER,this._currentFramebuffer),n};bi.prototype._readTexturePixels=function(s,e,t,i=-1,r=0,n=null,a=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(s,e,t,i,r,n,a,o,l,c))};class $r extends lv{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=gh()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=$r.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new Ae,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?$r._IsScene(e)?this._scene=e:this._engine=e:this._scene=Rt.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return he.IdentityReadOnly}getReflectionTextureMatrix(){return he.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,n,a){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!n,t),c=o.getLoadedTexturesCache();for(let u=0;u=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=qe.Serialize(this);return qe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let r=0;r{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}$r.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;F([X()],$r.prototype,"uniqueId",void 0);F([X()],$r.prototype,"name",void 0);F([X()],$r.prototype,"metadata",void 0);F([X("hasAlpha")],$r.prototype,"_hasAlpha",void 0);F([X("getAlphaFromRGB")],$r.prototype,"_getAlphaFromRGB",void 0);F([X()],$r.prototype,"level",void 0);F([X("coordinatesIndex")],$r.prototype,"_coordinatesIndex",void 0);F([X()],$r.prototype,"optimizeUVAllocation",void 0);F([X("coordinatesMode")],$r.prototype,"_coordinatesMode",void 0);F([X()],$r.prototype,"wrapU",null);F([X()],$r.prototype,"wrapV",null);F([X()],$r.prototype,"wrapR",void 0);F([X()],$r.prototype,"anisotropicFilteringLevel",void 0);F([X()],$r.prototype,"isCube",null);F([X()],$r.prototype,"is3D",null);F([X()],$r.prototype,"is2DArray",null);F([X()],$r.prototype,"gammaSpace",null);F([X()],$r.prototype,"invertZ",void 0);F([X()],$r.prototype,"lodLevelInAlpha",void 0);F([X()],$r.prototype,"lodGenerationOffset",null);F([X()],$r.prototype,"lodGenerationScale",null);F([X()],$r.prototype,"linearSpecularLOD",null);F([ii()],$r.prototype,"irradianceTexture",null);F([X()],$r.prototype,"isRenderTarget",void 0);function FJ(s,e,t=!1){const i=e.width,r=e.height;if(s instanceof Float32Array){let c=s.byteLength/s.BYTES_PER_ELEMENT;const u=new Uint8Array(c);for(;--c>=0;){let h=s[c];h<0?h=0:h>1&&(h=1),u[c]=h*255}s=u}const n=document.createElement("canvas");n.width=i,n.height=r;const a=n.getContext("2d");if(!a)return null;const o=a.createImageData(i,r);if(o.data.set(s),a.putImageData(o,0,0),t){const c=document.createElement("canvas");c.width=i,c.height=r;const u=c.getContext("2d");return u?(u.translate(0,r),u.scale(1,-1),u.drawImage(n,0,0),c.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Ege(s,e=0,t=0){const i=s.getInternalTexture();if(!i)return null;const r=s._readPixelsSync(e,t);return r?FJ(r,s.getSize(),i.invertY):null}async function Tge(s,e=0,t=0){const i=s.getInternalTexture();if(!i)return null;const r=await s.readPixels(e,t);return r?FJ(r,s.getSize(),i.invertY):null}const d2t={GenerateBase64StringFromPixelData:FJ,GenerateBase64StringFromTexture:Ege,GenerateBase64StringFromTextureAsync:Tge};class xe extends $r{static _CreateVideoTexture(e,t,i,r=!1,n=!1,a=xe.TRILINEAR_SAMPLINGMODE,o={},l,c=5){throw vi("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,n=xe.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=null,c=!1,u,h,d,f,p){super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new Ae,this._isBlocking=!0,this.name=e||"",this.url=e;let m,g=!1,_=null,y=!0;typeof i=="object"&&i!==null?(m=i.noMipmap??!1,r=i.invertY??!Qr,n=i.samplingMode??xe.TRILINEAR_SAMPLINGMODE,a=i.onLoad??null,o=i.onError??null,l=i.buffer??null,c=i.deleteBuffer??!1,u=i.format,h=i.mimeType,d=i.loaderOptions,f=i.creationFlags,g=i.useSRGBBuffer??!1,_=i.internalTexture??null,y=i.gammaSpace??y):m=!!i,this._gammaSpace=y,this._noMipmap=m,this._invertY=r===void 0?!Qr:r,this._initialSamplingMode=n,this._buffer=l,this._deleteBuffer=c,this._mimeType=h,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=g,this._forcedExtension=p,u&&(this._format=u);const v=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const A=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&v&&v.resetCachedMaterial()},b=(C,T)=>{this._loadingError=!0,this._errorObject={message:C,exception:T},o&&o(C,T),xe.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!_){this._delayedOnLoad=A,this._delayedOnError=b;return}if(this._texture=_??this._getFromCache(this.url,m,n,this._invertY,g,this.isCube),this._texture)if(this._texture.isReady)ew.SetImmediate(()=>A());else{const C=this._texture.onLoadedObservable.add(A);this._texture.onErrorObservable.add(T=>{var w;b(T.message,T.exception),(w=this._texture)==null||w.onLoadedObservable.remove(C)})}else if(!v||!v.useDelayedTextureLoading){try{this._texture=x.createTexture(this.url,m,this._invertY,v,n,A,b,this._buffer,void 0,this._format,this._forcedExtension,h,d,f,g)}catch(C){throw b("error loading",C),C}c&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=A,this._delayedOnError=b}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,n=>n.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?ew.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,D.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=he.Zero(),this._rowGenerationMatrix=new he,this._t0=D.Zero(),this._t1=D.Zero(),this._t2=D.Zero()),he.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(he.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,se.Matrix[0]),he.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,se.Matrix[1]),he.ScalingToRef(this._cachedUScale,this._cachedVScale,0,se.Matrix[2]),he.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,se.Matrix[3]),se.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(se.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(se.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(se.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),he.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,r=>r.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===xe.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=he.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=he.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case xe.PLANAR_MODE:{he.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case xe.PROJECTION_MODE:{he.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:he.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return qe.Clone(()=>new xe(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i;const e=this.name;xe.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(xe._SerializeInternalTextureUniqueId);return t?((xe.SerializeBuffers||xe.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+oz(this._buffer):(xe.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Ege(this):Tge(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,xe._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=((i=this._texture)==null?void 0:i.uniqueId)??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const c=VB.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&c.updateSamplingMode&&c._samplingMode&&c._samplingMode!==e.samplingMode&&c.updateSamplingMode(e.samplingMode),c}if(e.isCube&&!e.isRenderTarget)return xe._CubeTextureParser(e,t,i);const r=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!r)return null;let n;if(r){const l=t.getEngine().getLoadedTexturesCache();for(const c of l)if(c.uniqueId===e.internalTextureUniqueId){n=c;break}}const a=l=>{var c;if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){const u=e.samplingMode;l&&l.samplingMode!==u&&l.updateSamplingMode(u)}if(l&&e.animations)for(let u=0;u{let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const c=xe._CreateMirror(e.name,e.renderTargetSize,t,l);return c._waitingRenderList=e.renderList,c.mirrorPlane=Xl.FromArray(e.mirrorPlane),a(c),c}else if(e.isRenderTarget){let c=null;if(e.isCube){if(t.reflectionProbes)for(let u=0;u{a(c)},e._creationFlags??0,e._useSRGBBuffer??!1),c.name=e.name;else{let u;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?u=e.name:u=i+e.name,e.url&&(e.url.startsWith("data:")||xe.UseSerializedUrlIfAny)&&(u=e.url);const h={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{a(c)},internalTexture:n};c=new xe(u,t,h)}return c}},e,t)}static CreateFromBase64String(e,t,i,r,n,a=xe.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=5,u,h){return new xe("data:"+t,i,r,n,a,o,l,e,!1,c,void 0,void 0,u,h)}static LoadFromDataString(e,t,i,r=!1,n,a=!0,o=xe.TRILINEAR_SAMPLINGMODE,l=null,c=null,u=5,h,d){return e.substr(0,5)!=="data:"&&(e="data:"+e),new xe(e,i,n,a,o,l,c,t,r,u,void 0,void 0,h,d)}}xe.SerializeBuffers=!0;xe.ForceSerializeBuffers=!1;xe.OnTextureLoadErrorObservable=new Ae;xe._SerializeInternalTextureUniqueId=!1;xe._CubeTextureParser=(s,e,t)=>{throw vi("CubeTexture")};xe._CreateMirror=(s,e,t,i)=>{throw vi("MirrorTexture")};xe._CreateRenderTargetTexture=(s,e,t,i,r)=>{throw vi("RenderTargetTexture")};xe.NEAREST_SAMPLINGMODE=1;xe.NEAREST_NEAREST_MIPLINEAR=8;xe.BILINEAR_SAMPLINGMODE=2;xe.LINEAR_LINEAR_MIPNEAREST=11;xe.TRILINEAR_SAMPLINGMODE=3;xe.LINEAR_LINEAR_MIPLINEAR=3;xe.NEAREST_NEAREST_MIPNEAREST=4;xe.NEAREST_LINEAR_MIPNEAREST=5;xe.NEAREST_LINEAR_MIPLINEAR=6;xe.NEAREST_LINEAR=7;xe.NEAREST_NEAREST=1;xe.LINEAR_NEAREST_MIPNEAREST=9;xe.LINEAR_NEAREST_MIPLINEAR=10;xe.LINEAR_LINEAR=2;xe.LINEAR_NEAREST=12;xe.EXPLICIT_MODE=0;xe.SPHERICAL_MODE=1;xe.PLANAR_MODE=2;xe.CUBIC_MODE=3;xe.PROJECTION_MODE=4;xe.SKYBOX_MODE=5;xe.INVCUBIC_MODE=6;xe.EQUIRECTANGULAR_MODE=7;xe.FIXED_EQUIRECTANGULAR_MODE=8;xe.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;xe.CLAMP_ADDRESSMODE=0;xe.WRAP_ADDRESSMODE=1;xe.MIRROR_ADDRESSMODE=2;xe.UseSerializedUrlIfAny=!1;F([X()],xe.prototype,"url",void 0);F([X()],xe.prototype,"uOffset",void 0);F([X()],xe.prototype,"vOffset",void 0);F([X()],xe.prototype,"uScale",void 0);F([X()],xe.prototype,"vScale",void 0);F([X()],xe.prototype,"uAng",void 0);F([X()],xe.prototype,"vAng",void 0);F([X()],xe.prototype,"wAng",void 0);F([X()],xe.prototype,"uRotationCenter",void 0);F([X()],xe.prototype,"vRotationCenter",void 0);F([X()],xe.prototype,"wRotationCenter",void 0);F([X()],xe.prototype,"homogeneousRotationInUVTransform",void 0);F([X()],xe.prototype,"isBlocking",null);ve("BABYLON.Texture",xe);qe._TextureParser=xe.Parse;bi.prototype.updateRawTexture=function(s,e,t,i,r=null,n=0,a=!1){if(!s)return;const o=this._getRGBABufferInternalSizedFormat(n,t,a),l=this._getInternalFormat(t),c=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,s,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(s._bufferView=e,s.format=t,s.type=n,s.invertY=i,s._compression=r),s.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],s.width,s.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,s.width,s.height,0,l,c,e),s.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),s.isReady=!0};bi.prototype.createRawTexture=function(s,e,t,i,r,n,a,o=null,l=0,c=0,u=!1){const h=new zr(this,3);h.baseWidth=e,h.baseHeight=t,h.width=e,h.height=t,h.format=i,h.generateMipMaps=r,h.samplingMode=a,h.invertY=n,h._compression=o,h.type=l,h._useSRGBBuffer=this._getUseSRGBBuffer(u,!r),this._doNotHandleContextLost||(h._bufferView=s),this.updateRawTexture(h,s,i,n,o,l,h._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,h,!0);const d=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(h),h};bi.prototype.createRawCubeTexture=function(s,e,t,i,r,n,a,o=null){const l=this._gl,c=new zr(this,8);c.isCube=!0,c.format=t,c.type=i,this._doNotHandleContextLost||(c._bufferViewArray=s);const u=this._getWebGLTextureType(i);let h=this._getInternalFormat(t);h===l.RGB&&(h=l.RGBA),u===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(r=!1,a=1,fe.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):u===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(r=!1,a=1,fe.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):u===l.FLOAT&&!this._caps.textureFloatRender?(r=!1,fe.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):u===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(r=!1,fe.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const d=e,f=d;if(c.width=d,c.height=f,c.invertY=n,c._compression=o,!this.needPOTTextures||Fk(c.width)&&Fk(c.height)||(r=!1),s)this.updateRawCubeTexture(c,s,t,i,n,o);else{const g=this._getRGBABufferInternalSizedFormat(i),_=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(let y=0;y<6;y++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+y,_,this.getCaps().s3tc[o],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+y,_,g,c.width,c.height,0,h,u,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),s&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const m=this._getSamplingParameters(a,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,m.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,m.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=r,c.samplingMode=a,c.isReady=!0,c};bi.prototype.updateRawCubeTexture=function(s,e,t,i,r,n=null,a=0){s._bufferViewArray=e,s.format=t,s.type=i,s.invertY=r,s._compression=n;const o=this._gl,l=this._getWebGLTextureType(i);let c=this._getInternalFormat(t);const u=this._getRGBABufferInternalSizedFormat(i);let h=!1;c===o.RGB&&(c=o.RGBA,h=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,s,!0),this._unpackFlipY(r===void 0?!0:!!r),s.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let p=e[f];n?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,a,this.getCaps().s3tc[n],s.width,s.height,0,p):(h&&(p=B9e(p,s.width,s.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,a,u,s.width,s.height,0,c,l,p))}(!this.needPOTTextures||Fk(s.width)&&Fk(s.height))&&s.generateMipMaps&&a===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),s.isReady=!0};bi.prototype.createRawCubeTextureFromUrl=function(s,e,t,i,r,n,a,o,l=null,c=null,u=3,h=!1){const d=this._gl,f=this.createRawCubeTexture(null,t,i,r,!n,h,u,null);e==null||e.addPendingData(f),f.url=s,f.isReady=!1,this._internalTexturesCache.push(f);const p=(g,_)=>{e==null||e.removePendingData(f),c&&g&&c(g.status+" "+g.statusText,_)},m=g=>{const _=f.width,y=a(g);if(y){if(o){const v=this._getWebGLTextureType(r);let x=this._getInternalFormat(i);const A=this._getRGBABufferInternalSizedFormat(r);let b=!1;x===d.RGB&&(x=d.RGBA,b=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const C=o(y);for(let T=0;T>T;for(let P=0;P<6;P++){let M=C[T][P];b&&(M=B9e(M,w,w,r)),d.texImage2D(P,T,A,w,w,0,x,v,M)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,y,i,r,h);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(s,g=>{m(g)},void 0,e==null?void 0:e.offlineProvider,!0,p),f};function B9e(s,e,t,i){let r,n=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),n=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return(!this._transformMatrices||this._isDirty)&&this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let i=!0;for(const r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(const t of this.bones)if(t._linkedTransformNode){const i=t._linkedTransformNode;t.position=i.position,i.rotationQuaternion?t.rotationQuaternion=i.rotationQuaternion:t.rotation=i.rotation,t.scaling=i.scaling}}if(this.needInitialSkinMatrix)for(const t of this._meshesWithPoseMatrix){const i=t.getPoseMatrix();let r=this._isDirty;if((!t._bonesTransformMatrices||t._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(t._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),r=!0),!!r){if(this._synchronizedWithMesh!==t){this._synchronizedWithMesh=t;for(const n of this.bones)n.getParent()||(n.getBindMatrix().multiplyToRef(i,se.Matrix[1]),n._updateAbsoluteBindMatrices(se.Matrix[1]));if(this.isUsingTextureForMatrices){const n=(this.bones.length+1)*4;(!t._transformMatrixTexture||t._transformMatrixTexture.getSize().width!==n)&&(t._transformMatrixTexture&&t._transformMatrixTexture.dispose(),t._transformMatrixTexture=yn.CreateRGBATexture(t._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(t._bonesTransformMatrices,i),this.isUsingTextureForMatrices&&t._transformMatrixTexture&&t._transformMatrixTexture.update(t._bonesTransformMatrices)}}else{if(!this._isDirty)return;(!this._transformMatrices||this._transformMatrices.length!==16*(this.bones.length+1))&&(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=yn.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach(i=>{i.enableBlending=!0,i.blendingSpeed=e})})}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var t;const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(a.animation=r.animations[0].serialize()),e.ranges=[];for(const o in this._ranges){const l=this._ranges[o];if(!l)continue;const c={};c.name=o,c.from=l.from,c.to=l.to,e.ranges.push(c)}}return e}static Parse(e,t){const i=new cg(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=D.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let r;for(r=0;r-1&&(o=i.bones[n.parentBoneIndex]);const l=n.rest?he.FromArray(n.rest):null,c=new js(n.name,i,o,he.FromArray(n.matrix),l,null,a);n.id!==void 0&&n.id!==null&&(c.id=n.id),n.length&&(c.length=n.length),n.metadata&&(c.metadata=n.metadata),n.animation&&c.animations.push(tt.Parse(n.animation)),n.linkedTransformNodeId!==void 0&&n.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeId=n.linkedTransformNodeId)}if(e.ranges)for(r=0;r0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class f2t{constructor(e,t){this._scene=e,t instanceof cg?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce((o,l)=>o+l.to-l.from+1,0);if(isNaN(i))throw new Error("Invalid animation ranges.");let r=0;const n=(t+1)*4*4*i,a=new Float32Array(n);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const o of e)for(let l=o.from;l<=o.to;l++)await this._executeAnimationFrame(a,l,r++);return a}async _executeAnimationFrame(e,t,i){return new Promise((r,n)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,()=>{const a=this._skeleton.getTransformMatrices(this._mesh);e.set(a,i*a.length),r()})})}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=yn.CreateRGBATexture(e,(t+1)*4,e.length/((t+1)*4*4),this._scene,!1,!1,xe.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=(t+1)*4,r=e.length/((t+1)*4*4);return{vertexData:oz(e),width:i,height:r}}loadBakedVertexDataFromObject(e){return new Float32Array(lz(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class z9e{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===yt.POINTERDOWN){this._isPointerDown=!0;return}i.type===yt.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=Or.Now;let r=0;this._lastFrameTime!=null&&(r=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const n=i-this._lastInteractionTime-this._idleRotationWaitTime,a=Math.max(Math.min(n/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*a,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(r/1e3))})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??Or.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){const r=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=r*.05,this.upperRadiusTransitionRange=r*.05}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return this._attachedCamera?this._attachedCamera.radius===e&&!this._radiusIsAnimating:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(tx.EasingFunction.setEasingMode(tx.EasingMode),this._radiusBounceTransition=tt.CreateAnimation("radius",tt.ANIMATIONTYPE_FLOAT,60,tx.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=tt.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}tx.EasingFunction=new A9e(.3);tx.EasingMode=ya.EASINGMODE_EASEOUT;class hh{constructor(){this.onTargetFramingAnimationEndObservable=new Ae,this._mode=hh.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();hh.EasingFunction.setEasingMode(hh.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===yt.POINTERDOWN){this._isPointerDown=!0;return}i.type===yt.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const r=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let a=0;a{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),u&&this._animatables.push(u),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===hh.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=Or.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=tt.CreateAnimation("beta",tt.ANIMATIONTYPE_FLOAT,60,hh.EasingFunction));const r=tt.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});r&&this._animatables.push(r)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=Or.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}}hh.EasingFunction=new b9e;hh.EasingMode=ya.EASINGMODE_EASEINOUT;hh.IgnoreBoundsSizeMode=0;hh.FitFrustumSidesMode=1;class OI{constructor(e,t=new D,i=0,r=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=r}}class p2t{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new OI(D.Up()),new OI(D.Down()),new OI(D.Left()),new OI(D.Right()),new OI(D.Forward()),new OI(D.Forward().scaleInPlace(-1))],this._tmpMatrix=new he,this._tmpVector=new D,this._zeroVector=D.Zero(),this._lookAtTmpMatrix=new he}init(){}_closestFace(e){return this._faceVectors.forEach(t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=Pe.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),D.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=D.GetAngleBetweenVectors(t.rotatedDirection,e,D.Cross(t.rotatedDirection,e))}),this._faceVectors.reduce((t,i)=>t.ignore?i:i.ignore||t.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),D.TransformCoordinatesToRef(D.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach(n=>{i.direction.x&&n.direction.x&&(n.ignore=!0),i.direction.y&&n.direction.y&&(n.ignore=!0),i.direction.z&&n.direction.z&&(n.ignore=!0)});const r=this._closestFace(this._tmpVector);this._faceVectors.forEach(n=>{n.ignore=!1}),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=Pe.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,r.rotatedDirection,this._ui.rotationQuaternion),r.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),r.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),r.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)})}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class m2t{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time){this._hoverValue=this._time,this._detachObserver();return}}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0)){this._hoverValue=0,this._detachObserver();return}this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),!(this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0))&&(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach(i=>{this._setAllVisibility(i,t)})}_attachObserver(){var e;this._onBeforeRenderObserver||(this._onBeforeRenderObserver=(e=this._ownerNode)==null?void 0:e.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){var e;this._onBeforeRenderObserver&&((e=this._ownerNode)==null||e.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class $i{constructor(e,t,i=Number.MAX_VALUE,r=ci){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new $i(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const r=$i._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),n=$i._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let a=0,o=Number.MAX_VALUE,l,c,u,h;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xn.x)return!1}else if(l=1/this.direction.x,c=(r.x-this.origin.x)*l,u=(n.x-this.origin.x)*l,u===-1/0&&(u=1/0),c>u&&(h=c,c=u,u=h),a=Math.max(c,a),o=Math.min(u,o),a>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yn.y)return!1}else if(l=1/this.direction.y,c=(r.y-this.origin.y)*l,u=(n.y-this.origin.y)*l,u===-1/0&&(u=1/0),c>u&&(h=c,c=u,u=h),a=Math.max(c,a),o=Math.min(u,o),a>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zn.z)return!1}else if(l=1/this.direction.z,c=(r.z-this.origin.z)*l,u=(n.z-this.origin.z)*l,u===-1/0&&(u=1/0),c>u&&(h=c,c=u,u=h),a=Math.max(c,a),o=Math.min(u,o),a>o)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,n=e.center.z-this.origin.z,a=i*i+r*r+n*n,o=e.radius+t,l=o*o;if(a<=l)return!0;const c=i*this.direction.x+r*this.direction.y+n*this.direction.z;return c<0?!1:a-c*c<=l}intersectsTriangle(e,t,i){const r=$i._TmpVector3[0],n=$i._TmpVector3[1],a=$i._TmpVector3[2],o=$i._TmpVector3[3],l=$i._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,n),D.CrossToRef(this.direction,n,a);const c=D.Dot(r,a);if(c===0)return null;const u=1/c;this.origin.subtractToRef(e,o);const h=D.Dot(o,a)*u;if(h<-this.epsilon||h>1+this.epsilon)return null;D.CrossToRef(o,r,l);const d=D.Dot(this.direction,l)*u;if(d<-this.epsilon||h+d>1+this.epsilon)return null;const f=D.Dot(n,l)*u;return f>this.length?null:new lZ(1-h-d,h,f)}intersectsPlane(e){let t;const i=D.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const r=D.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const i=(this.origin.y-t)/this.direction.y;return i>0?null:new D(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{const i=(this.origin.x-t)/this.direction.x;return i>0?null:new D(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{const i=(this.origin.z-t)/this.direction.z;return i>0?null:new D(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,r=!1,n,a=!1){const o=se.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?$i.TransformToRef(this,o,this._tmpRay):this._tmpRay=$i.Transform(this,o),e.intersects(this._tmpRay,t,i,r,n,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){const r=this.origin,n=se.Vector3[0],a=se.Vector3[1],o=se.Vector3[2],l=se.Vector3[3];t.subtractToRef(e,n),this.direction.scaleToRef($i._Rayl,o),r.addToRef(o,a),e.subtractToRef(r,l);const c=D.Dot(n,n),u=D.Dot(n,o),h=D.Dot(o,o),d=D.Dot(n,l),f=D.Dot(o,l),p=c*h-u*u;let m,g=p,_,y=p;p<$i._Smallnum?(m=0,g=1,_=f,y=h):(m=u*f-h*d,_=c*f-u*d,m<0?(m=0,_=f,y=h):m>g&&(m=g,_=f+u,y=h)),_<0?(_=0,-d<0?m=0:-d>c?m=g:(m=-d,g=c)):_>y&&(_=y,-d+u<0?m=0:-d+u>c?m=g:(m=-d+u,g=c));const v=Math.abs(m)<$i._Smallnum?0:m/g,x=Math.abs(_)<$i._Smallnum?0:_/y,A=se.Vector3[4];o.scaleToRef(x,A);const b=se.Vector3[5];n.scaleToRef(v,b),b.addInPlace(l);const C=se.Vector3[6];return b.subtractToRef(A,C),x>0&&x<=this.length&&C.lengthSquared()=s.distance?null:c};gt.prototype._internalPick=function(s,e,t,i,r){let n=null;const a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=$i.Zero()),this.createPickingRayToRef(s,e,a,this._tempPickingRay,r||null),this._tempPickingRay),t,i,!0);return n&&(n.ray=this.createPickingRay(s,e,he.Identity(),r||null)),n};Object.defineProperty(gt.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});gt.prototype.pick=function(s,e,t,i,r,n,a=!1){const o=this._internalPick((l,c)=>(this._tempPickingRay||(this._tempPickingRay=$i.Zero()),this.createPickingRayToRef(s,e,l,this._tempPickingRay,r||null,!1,c),this._tempPickingRay),t,i,!1,n);return o&&(o.ray=this.createPickingRay(s,e,he.Identity(),r||null)),o};gt.prototype.pickWithRay=function(s,e,t,i){const r=this._internalPick(n=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=he.Identity()),n.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=$i.Zero()),$i.TransformToRef(s,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return r&&(r.ray=s),r};gt.prototype.multiPick=function(s,e,t,i,r){return this._internalMultiPick(n=>this.createPickingRay(s,e,n,i||null),t,r)};gt.prototype.multiPickWithRay=function(s,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=he.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=$i.Zero()),$i.TransformToRef(s,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};Nt.prototype.getForwardRay=function(s=100,e,t){return this.getForwardRayToRef(new $i(D.Zero(),D.Zero(),s),s,e,t)};Nt.prototype.getForwardRayToRef=function(s,e=100,t,i){t||(t=this.getWorldMatrix()),s.length=e,i?s.origin.copyFrom(i):s.origin.copyFrom(this.position);const r=se.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=se.Vector3[3];return D.TransformNormalToRef(r,t,n),D.NormalizeToRef(n,s.direction),s};class ds{static _RemoveAndStorePivotPoint(e){e&&ds._PivotCached===0&&(e.getPivotPointToRef(ds._OldPivotPoint),ds._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,ds._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(he.IdentityReadOnly),ds._OldPivotPoint.subtractToRef(e.getPivotPoint(),ds._PivotTranslation),ds._PivotTmpVector.copyFromFloats(1,1,1),ds._PivotTmpVector.subtractInPlace(e.scaling),ds._PivotTmpVector.multiplyInPlace(ds._PivotTranslation),e.position.addInPlace(ds._PivotTmpVector))),ds._PivotCached++}static _RestorePivotPoint(e){e&&!ds._OldPivotPoint.equalsToFloats(0,0,0)&&ds._PivotCached===1&&(e.setPivotPoint(ds._OldPivotPoint),e._postMultiplyPivotMatrix=ds._PivotPostMultiplyPivotMatrix,ds._PivotTmpVector.copyFromFloats(1,1,1),ds._PivotTmpVector.subtractInPlace(e.scaling),ds._PivotTmpVector.multiplyInPlace(ds._PivotTranslation),e.position.subtractInPlace(ds._PivotTmpVector)),this._PivotCached--}}ds._PivotCached=0;ds._OldPivotPoint=new D;ds._PivotTranslation=new D;ds._PivotTmpVector=new D;ds._PivotPostMultiplyPivotMatrix=!1;function vz(s){const e=[],t=[],i=[],r=[],n=s.width||s.size||1,a=s.height||s.size||1,o=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,l=n/2,c=a/2;t.push(-l,-c,0),i.push(0,0,-1),r.push(0,Qr?1:0),t.push(l,-c,0),i.push(0,0,-1),r.push(1,Qr?1:0),t.push(l,c,0),i.push(0,0,-1),r.push(1,Qr?0:1),t.push(-l,c,0),i.push(0,0,-1),r.push(0,Qr?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),at._ComputeSides(o,t,e,i,r,s.frontUVs,s.backUVs);const u=new at;return u.indices=e,u.positions=t,u.normals=i,u.uvs=r,u}function b_(s,e={},t=null){const i=new Ee(s,t);return e.sideOrientation=Ee._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,vz(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}const g2t={CreatePlane:b_};at.CreatePlane=vz;Ee.CreatePlane=(s,e,t,i,r)=>b_(s,{size:e,width:e,height:e,sideOrientation:r,updatable:i},t);class sl{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new Ae,this.onDragStartObservable=new Ae,this.onDragEndObservable=new Ae,this.onEnabledObservable=new Ae,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=i=>!0,this._tmpVector=new D(0,0,0),this._alternatePickedPoint=new D(0,0,0),this._worldDragAxis=new D(0,0,0),this._targetPosition=new D(0,0,0),this._attachedToElement=!1,this._startDragRay=new $i(new D,new D),this._lastPointerRay={},this._dragDelta=new D,this._pointA=new D(0,0,0),this._pointC=new D(0,0,0),this._localAxis=new D(0,0,0),this._lookAt=new D(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,sl._PlaneScene||(this._debugMode?sl._PlaneScene=this._scene:(sl._PlaneScene=new gt(this._scene.getEngine(),{virtual:!0}),sl._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{sl._PlaneScene.dispose(),sl._PlaneScene=null}))),this._dragPlane=b_("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Ee.DOUBLESIDE},sl._PlaneScene),this.lastDragPosition=new D(0,0,0);const i=t||(r=>this.attachedNode==r||r.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(r=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(r.type==yt.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&r.pickInfo&&r.pickInfo.hit&&r.pickInfo.pickedMesh&&r.pickInfo.pickedPoint&&r.pickInfo.ray&&i(r.pickInfo.pickedMesh)&&this._activeDragButton===-1&&this.dragButtons.indexOf(r.event.button)!==-1&&(this._activeDragButton=r.event.button,this._activePointerInfo=r,this._startDrag(r.event.pointerId,r.pickInfo.ray,r.pickInfo.pickedPoint));else if(r.type==yt.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==r.event.pointerId&&(this._activeDragButton===r.event.button||this._activeDragButton===-1)&&this.releaseDrag();else if(r.type==yt.POINTERMOVE){const n=r.event.pointerId;if(this.currentDraggingPointerId===sl._AnyMouseId&&n!==sl._AnyMouseId){const a=r.event;(a.pointerType==="mouse"||!this._scene.getEngine().hostInformation.isMobile&&a instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[n]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=n)}this._lastPointerRay[n]||(this._lastPointerRay[n]=new $i(new D,new D)),r.pickInfo&&r.pickInfo.ray&&(this._lastPointerRay[n].origin.copyFrom(r.pickInfo.ray.origin),this._lastPointerRay[n].direction.copyFrom(r.pickInfo.ray.direction),this.currentDraggingPointerId==n&&this.dragging&&this._moveDrag(r.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let r=!1;ds._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),r=!0),ds._RestorePivotPoint(this.attachedNode),r&&this.attachedNode.computeWorldMatrix()}})}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if(this._scene.activeCamera.getClassName()==="ArcRotateCamera"){const e=this._scene.activeCamera;e.attachControl(e.inputs?e.inputs.noPreventDefault:!0,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs?this._scene.activeCamera.inputs.noPreventDefault:!0);this._attachedToElement=!1}}startDrag(e=sl._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===sl._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;ds._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),ds._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){ds._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?D.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=D.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),ds._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(D.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle)if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*D.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const l=D.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-l,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}else return null;const i=this._dragPlane.forward,r=this._dragPlane.position,n=e.direction.dot(i);if(Math.abs(n).999?Math.abs(D.Dot(D.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(D.Right()):this._lookAt.copyFrom(D.UpReadOnly):(D.CrossToRef(this._localAxis,this._pointC,this._lookAt),D.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?D.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}sl._AnyMouseId=-2;class _2t{constructor(){this._startDistance=0,this._initialScale=new D(0,0,0),this._targetScale=new D(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new sl({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new sl({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add(()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))}),this._dragBehaviorB.onDragStartObservable.add(()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))}),[this._dragBehaviorA,this._dragBehaviorB].forEach(t=>{t.onDragObservable.add(()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const i=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(i,this._targetScale)}})}),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}})}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach(e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)})}}class I1{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new D,this._tmpQuaternion=new Pe,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this.allowMultiPointer=!0}get currentDraggingPointerId(){return this.currentDraggingPointerIds[0]!==void 0?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new _t("",I1._virtualScene);e.rotationQuaternion=new Pe;const t=new _t("",I1._virtualScene);t.rotationQuaternion=new Pe;const i=new _t("",I1._virtualScene);return i.rotationQuaternion=new Pe,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new D,startingPivotOrientation:new Pe,startingPosition:new D,startingOrientation:new Pe,lastOriginPosition:new D,lastDragPosition:new D}}_resetVirtualMeshesPosition(){for(let e=0;ef&&(f=Math.min(p-h,0)),u.scaleInPlace(f),u.addToRef(n.pivotMesh.absolutePosition,this._tmpVector),n.pivotMesh.setAbsolutePosition(this._tmpVector),u.addToRef(n.dragMesh.absolutePosition,this._tmpVector),n.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),I1._virtualScene||(I1._virtualScene=new gt(this._scene.getEngine(),{virtual:!0}),I1._virtualScene.detachControl());const t=i=>this._ownerNode===i||i.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||this.draggableMeshes.indexOf(i)!==-1);this._pointerObserver=this._scene.onPointerObservable.add(i=>{const r=i.event.pointerId;this._virtualMeshesInfo[r]||(this._virtualMeshesInfo[r]=this._createVirtualMeshInfo());const n=this._virtualMeshesInfo[r],a=i.event.pointerType==="xr-near"||i.event.pointerType==="xr";if(i.type==yt.POINTERDOWN){if(!n.dragging&&i.pickInfo&&i.pickInfo.hit&&i.pickInfo.pickedMesh&&i.pickInfo.pickedPoint&&i.pickInfo.ray&&(!a||i.pickInfo.aimTransform)&&t(i.pickInfo.pickedMesh)){if((!this.allowMultiPointer||a)&&this.currentDraggingPointerIds.length>0)return;this._pointerCamera&&this._pointerCamera.cameraRigMode===Nt.RIG_MODE_NONE&&!this._pointerCamera._isLeftCamera&&!this._pointerCamera._isRightCamera&&i.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const o=this._virtualMeshesInfo[r];a?(this._dragging=i.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,o.originMesh.position.copyFrom(i.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&i.pickInfo.gripTransform?o.originMesh.rotationQuaternion.copyFrom(i.pickInfo.gripTransform.rotationQuaternion):o.originMesh.rotationQuaternion.copyFrom(i.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,o.originMesh.position.copyFrom(i.pickInfo.ray.origin)),o.lastOriginPosition.copyFrom(o.originMesh.position),o.dragMesh.position.copyFrom(i.pickInfo.pickedPoint),o.lastDragPosition.copyFrom(i.pickInfo.pickedPoint),o.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),o.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),o.startingPosition.copyFrom(o.dragMesh.position),o.startingPivotPosition.copyFrom(o.pivotMesh.position),o.startingOrientation.copyFrom(o.dragMesh.rotationQuaternion),o.startingPivotOrientation.copyFrom(o.pivotMesh.rotationQuaternion),a?(o.originMesh.addChild(o.dragMesh),o.originMesh.addChild(o.pivotMesh)):o.originMesh.lookAt(o.dragMesh.position),o.dragging=!0,this.currentDraggingPointerIds.indexOf(r)===-1&&this.currentDraggingPointerIds.push(r),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):(!this.allowMultiPointer||this.currentDraggingPointerIds.length===0)&&(this._attachedToElement=!1)),this._targetDragStart(o.pivotMesh.position,o.pivotMesh.rotationQuaternion,r),this.onDragStartObservable.notifyObservers({position:o.pivotMesh.position})}}else if(i.type==yt.POINTERUP||i.type==yt.POINTERDOUBLETAP){const o=this.currentDraggingPointerIds.indexOf(r);n.dragging=!1,o!==-1&&(this.currentDraggingPointerIds.splice(o,1),this.currentDraggingPointerIds.length===0&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),n.originMesh.removeChild(n.dragMesh),n.originMesh.removeChild(n.pivotMesh),this._targetDragEnd(r),this.onDragEndObservable.notifyObservers({}))}else if(i.type==yt.POINTERMOVE&&this.currentDraggingPointerIds.indexOf(r)!==-1&&n.dragging&&i.pickInfo&&(i.pickInfo.ray||i.pickInfo.aimTransform)){let l=this.zDragFactor;(this.currentDraggingPointerIds.length>1||i.pickInfo.originMesh)&&(l=0),this._ownerNode.computeWorldMatrix(!0),a?this._pointerUpdateXR(i.pickInfo.aimTransform,i.pickInfo.gripTransform,r,l):this._pointerUpdate2D(i.pickInfo.ray,r,l),this._tmpQuaternion.copyFrom(n.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,n.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),n.pivotMesh.absolutePosition.subtractToRef(n.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:n.pivotMesh.position,pickInfo:i.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,r),n.lastDragPosition.copyFrom(n.dragMesh.absolutePosition),this._moving=!0}})}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if(this._pointerCamera.getClassName()==="ArcRotateCamera"){const e=this._pointerCamera;e.attachControl(e.inputs?e.inputs.noPreventDefault:!0,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(this._pointerCamera.inputs?this._pointerCamera.inputs.noPreventDefault:!0)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class V9e extends I1{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new D(0,0,0),this._targetOrientation=new Pe,this._targetScaling=new D(1,1,1),this._startingPosition=new D(0,0,0),this._startingOrientation=new Pe,this._startingScaling=new D(1,1,1),this.onPositionChangedObservable=new Ae,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach(t=>{t.isNearGrabbable=!0}),this._virtualTransformNode=new _t("virtual_sixDof",I1._virtualScene),this._virtualTransformNode.rotationQuaternion=Pe.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(()=>{if(this.currentDraggingPointerIds.length===1&&this._moving&&!this.disableMovement){const t=se.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=se.Vector3[1];if(i.copyFrom(t),e.parent){const r=se.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(r),r.invert(),D.TransformNormalToRef(t,r,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const r=se.Quaternion[0];if(r.copyFrom(this._targetOrientation),e.parent){const n=se.Quaternion[0];n.copyFrom(e.parent.absoluteRotationQuaternion),n.invertInPlace(),n.multiplyToRef(this._targetOrientation,r)}Pe.SlerpToRef(e.rotationQuaternion,r,this.dragDeltaRatio,e.rotationQuaternion)}}})}_getPositionOffsetAround(e,t,i){const r=se.Matrix[0],n=se.Matrix[1],a=se.Matrix[2],o=se.Matrix[3],l=se.Matrix[4];return he.TranslationToRef(e.x,e.y,e.z,r),he.TranslationToRef(-e.x,-e.y,-e.z,n),he.FromQuaternionToRef(i,a),he.ScalingToRef(t,t,t,o),n.multiplyToRef(a,l),l.multiplyToRef(o,l),l.multiplyToRef(r,l),l.getTranslation()}_onePointerPositionUpdated(e,t){se.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?Pe.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,se.Quaternion[0]):se.Quaternion[0].copyFrom(t),se.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=se.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const r=se.Vector3[1];t.subtractToRef(e,r);const n=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,a=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=se.Vector3[2];n.addToRef(a,o),o.scaleInPlace(.5);const l=se.Vector3[3];a.subtractToRef(n,l);const c=l.length()/r.length(),u=o.subtract(i),h=Pe.FromEulerAngles(0,D.GetAngleBetweenVectorsOnPlane(r.normalize(),l.normalize(),D.UpReadOnly),0),d=this._ownerNode.parent;this._ownerNode.setParent(null);const f=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),c,h);this._virtualTransformNode.rotationQuaternion.multiplyToRef(h,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(c,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(u.addInPlace(f),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(d)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=Pe.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(e===1){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const i=se.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,i),i.normalize();const r=se.Quaternion[0];this._scene.useRightHandedSystem?Pe.FromLookDirectionRHToRef(i,new D(0,1,0),r):Pe.FromLookDirectionLHToRef(i,new D(0,1,0),r),r.normalize(),Pe.RotationYawPitchRollToRef(r.toEulerAngles().y,0,0,se.Quaternion[0]),this._targetOrientation.copyFrom(se.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else e===2&&(this._virtualTransformNode.setPivotPoint(new D(0,0,0),0),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,1),this._resetVirtualMeshesPosition())}_targetDrag(e,t){this.currentDraggingPointerIds.length===1?this._onePointerPositionUpdated(e,t):this.currentDraggingPointerIds.length===2&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(this.currentDraggingPointerIds.length===1){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class v2t{constructor(){this._attachPointLocalOffset=new D,this._workingPosition=new D,this._workingQuaternion=new Pe,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=Pe.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const r=se.Vector3[0];return r.copyFrom(t),r.scaleInPlace(this.hitNormalOffset),r.addInPlace(i),this._attachedMesh.parent&&(se.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),D.TransformNormalToRef(r,se.Matrix[0],r)),{position:r,quaternion:Pe.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const i=this._getTargetPose(t);i&&D.Distance(this._attachedMesh.position,i.position){this.enabled&&e.type==yt.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)}),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add(()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e})}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}class y2t{constructor(){this._tmpQuaternion=new Pe,this._tmpVectors=[new D,new D,new D,new D,new D,new D,new D],this._tmpMatrix=new he,this._tmpInvertView=new he,this._tmpForward=new D,this._tmpNodeForward=new D,this._tmpPosition=new D,this._workingPosition=new D,this._workingQuaternion=new Pe,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(D.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,r=this.maximumDistance;const n=this.defaultDistance,a=this._tmpVectors[0];a.copyFrom(e);let o=a.length();if(a.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(a)*i,r=this._length2D(a)*r;const c=this._length2D(e);a.scaleInPlace(o/c),o=c}let l=o;return t?l=n:l=At.Clamp(o,i,r),e.copyFrom(a).scaleInPlace(l),o!==l}_applyVerticalClamp(e){this.verticalMaxDistance!==0&&(e.y=At.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){Pe.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),D.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),D.TransformNormalToRef(i,e,i),Pe.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const r=this._tmpVectors[6];r.copyFromFloats(1,0,0),D.TransformNormalToRef(i,e,i),D.TransformNormalToRef(r,e,r);const n=D.UpReadOnly;if(t.length()d&&(Pe.RotationAxisToRef(r,-h+d,l),t.rotateByQuaternionToRef(l,t),o=!0)}const c=this._angleBetweenVectorAndPlane(t,r)*(this._scene.useRightHandedSystem?-1:1),u=this.maxViewHorizontalDegrees*Math.PI/180*.5;return c<-u?(Pe.RotationAxisToRef(n,-c-u,l),t.rotateByQuaternionToRef(l,t),o=!0):c>u&&(Pe.RotationAxisToRef(n,-c+u,l),t.rotateByQuaternionToRef(l,t),o=!0),o}_orientationClamp(e,t){var o;const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const r=this._tmpVectors[1],n=this._tmpVectors[2];r.copyFromFloats(0,1,0),D.CrossToRef(i,r,n);const a=n.length();athis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),r=this._workingPosition,n=this._workingQuaternion,a=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),D.TransformCoordinatesToRef(a,i,r);const l=this._tmpPosition;l.copyFromFloats(0,0,0),D.TransformCoordinatesToRef(l,i,l),l.scaleInPlace(-1).subtractInPlace(a),r.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let c=!1;const u=this._tmpForward;u.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),D.TransformNormalToRef(u,o,u);const h=this._tmpNodeForward;if(h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),D.TransformNormalToRef(h,i,h),this._recenterNextUpdate)r.copyFrom(u).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const f=r.length();r.copyFrom(u).scaleInPlace(f)}else c=this._angularClamp(o,r);let d=!1;this.ignoreDistanceClamp||(d=this._distanceClamp(r,c),this._applyVerticalClamp(r)),this.useFixedVerticalOffset&&(r.y=l.y-e.globalPosition.y+this.fixedVerticalOffset),(c||d||this._passedOrientationDeadzone(r,h)||this._recenterNextUpdate)&&this._orientationClamp(r,n),this._workingPosition.subtractInPlace(a),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=Pe.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose){this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);return}const i=new D;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),D.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const r=new Pe;r.copyFrom(this.attachedNode.rotationQuaternion),Pe.SmoothToRef(r,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add(()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e})}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class wr{}wr.ANCHOR_SYSTEM="xr-anchor-system";wr.BACKGROUND_REMOVER="xr-background-remover";wr.HIT_TEST="xr-hit-test";wr.MESH_DETECTION="xr-mesh-detection";wr.PHYSICS_CONTROLLERS="xr-physics-controller";wr.PLANE_DETECTION="xr-plane-detection";wr.POINTER_SELECTION="xr-controller-pointer-selection";wr.TELEPORTATION="xr-controller-teleportation";wr.FEATURE_POINTS="xr-feature-points";wr.HAND_TRACKING="xr-hand-tracking";wr.IMAGE_TRACKING="xr-image-tracking";wr.NEAR_INTERACTION="xr-near-interaction";wr.DOM_OVERLAY="xr-dom-overlay";wr.MOVEMENT="xr-controller-movement";wr.LIGHT_ESTIMATION="xr-light-estimation";wr.EYE_TRACKING="xr-eye-tracking";wr.WALKING_LOCOMOTION="xr-walking-locomotion";wr.LAYERS="xr-layers";wr.DEPTH_SENSING="xr-depth-sensing";wr.SPACE_WARP="xr-space-warp";wr.RAW_CAMERA_ACCESS="xr-raw-camera-access";class Yn{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(t=>{const i=this._features[t];i.enabled&&!i.featureImplementation.attached&&!i.featureImplementation.disableAutoAttach&&this.attachFeature(t)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(t=>{const i=this._features[t];i.enabled&&i.featureImplementation.attached&&this.detachFeature(t)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){const n=this._AvailableFeatures[e][t];if(!n)throw new Error("feature not found");return n(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Me.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Me.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t=typeof e=="string"?e:e.Name,i=this._features[t];return i&&i.enabled?(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0):!1}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,n=!0){const a=typeof e=="string"?e:e.Name;let o=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${a} (${t})`);if(t==="stable"?o=Yn.GetStableVersionOfFeature(a):t==="latest"?o=Yn.GetLatestVersionOfFeature(a):o=+t,o===-1||isNaN(o))throw new Error(`feature not found - ${a} (${t})`)}else o=t;const l=Yn._ConflictingFeatures[a];if(l!==void 0&&this.getEnabledFeatures().indexOf(l)!==-1)throw new Error(`Feature ${a} cannot be enabled while ${l} is enabled.`);const c=this._features[a],u=Yn.ConstructFeature(a,o,this._xrSessionManager,i);if(!u)throw new Error(`feature not found - ${a}`);c&&this.disableFeature(a);const h=u();if(h.dependsOn&&!h.dependsOn.every(f=>!!this._features[f]))throw new Error(`Dependant features missing. Make sure the following features are enabled - ${h.dependsOn.join(", ")}`);if(h.isCompatible())return this._features[a]={featureImplementation:h,enabled:!0,version:o,required:n},r?this._xrSessionManager.session&&!this._features[a].featureImplementation.attached&&this.attachFeature(a):this._features[a].featureImplementation.disableAutoAttach=!0,this._features[a].featureImplementation;if(n)throw new Error("required feature not compatible");return Me.Warn(`Feature ${a} not compatible with the current environment/browser and was not enabled.`),h}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const r=this._features[i],n=r.featureImplementation.xrNativeFeatureName;if(n&&(r.required?(e.requiredFeatures=e.requiredFeatures||[],e.requiredFeatures.indexOf(n)===-1&&e.requiredFeatures.push(n)):(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.indexOf(n)===-1&&e.optionalFeatures.push(n))),r.featureImplementation.getXRSessionInitExtension){const a=await r.featureImplementation.getXRSessionInitExtension();e={...e,...a}}}return e}}Yn._AvailableFeatures={};Yn._ConflictingFeatures={[wr.TELEPORTATION]:wr.MOVEMENT,[wr.MOVEMENT]:wr.TELEPORTATION};var Lue;(function(s){s[s.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",s[s.RADIAL_SIDE=1]="RADIAL_SIDE",s[s.ULNAR_SIDE=2]="ULNAR_SIDE",s[s.BELOW_WRIST=3]="BELOW_WRIST"})(Lue||(Lue={}));var Oue;(function(s){s[s.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",s[s.HAND_ROTATION=1]="HAND_ROTATION"})(Oue||(Oue={}));var Nue;(function(s){s[s.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",s[s.PALM_UP=1]="PALM_UP",s[s.GAZE_FOCUS=2]="GAZE_FOCUS",s[s.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(Nue||(Nue={}));class x2t{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=3,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=2,this.zoneOrientationMode=1,this.nodeOrientationMode=1,this.handedness="none",this.lerpTime=100,this._zoneAxis[0]=new D(0,1,0),this._zoneAxis[1]=new D(-1,0,0),this._zoneAxis[2]=new D(1,0,0),this._zoneAxis[3]=new D(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(this.handedness==="none"?e=this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):e=this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh("pinky-finger-metacarpal"),i=e.getJointMesh("middle-finger-metacarpal"),r=e.getJointMesh("wrist");if(r&&i&&t){const n={position:i.absolutePosition,quaternion:new Pe,id:e.xrController.uniqueId},a=se.Vector3[0],o=se.Vector3[1],l=se.Vector3[2];return a.copyFrom(i.absolutePosition).subtractInPlace(r.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),D.CrossToRef(a,o,o),D.CrossToRef(o,a,l),Pe.FromLookDirectionLHToRef(o,a,n.quaternion),n}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=Pe.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{const i=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,i){const r=se.Vector3[0],n=this._scene.activeCamera;r.copyFrom(this._zoneAxis[this.targetZone]);const a=se.Quaternion[0];if(n&&(this.zoneOrientationMode===0||this.nodeOrientationMode===0)){const u=se.Vector3[1];u.copyFrom(n.position).subtractInPlace(i.position).normalize(),this._scene.useRightHandedSystem?Pe.FromLookDirectionRHToRef(u,D.UpReadOnly,a):Pe.FromLookDirectionLHToRef(u,D.UpReadOnly,a)}this.zoneOrientationMode===1?i.quaternion.toRotationMatrix(se.Matrix[0]):a.toRotationMatrix(se.Matrix[0]),D.TransformNormalToRef(r,se.Matrix[0],r),r.scaleInPlace(this.targetOffset);const o=se.Vector3[2],l=se.Quaternion[1];o.copyFrom(i.position).addInPlace(r),this.nodeOrientationMode===1?l.copyFrom(i.quaternion):l.copyFrom(a);const c=Date.now()-t;D.SmoothToRef(this._node.position,o,c,this.lerpTime,this._node.position),Pe.SmoothToRef(this._node.rotationQuaternion,l,c,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=i.id}this._setVisibility(i),t=Date.now()})}_setVisibility(e){let t=!0,i=!0;const r=this._scene.activeCamera;if(r){const n=r.getForwardRay();if(this.handConstraintVisibility===2||this.handConstraintVisibility===3){i=!1;let a;this._eyeTracking&&(a=this._eyeTracking.getEyeGaze()),a=a||n;const o=se.Vector3[0];e?e.position.subtractToRef(a.origin,o):this._node.getAbsolutePosition().subtractToRef(a.origin,o);const l=D.Dot(o,a.direction),c=l*l;l>0&&o.lengthSquared()-cthis.palmUpStrictness*2-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(!t)Me.Error("XR features manager must be available or provided directly for the Hand Menu to work");else{try{this._eyeTracking=t.getEnabledFeature(wr.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(wr.HAND_TRACKING)}catch{Me.Error("Hand tracking must be enabled for the Hand Menu to work")}}}}class Dd{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=D.Zero(),this.poleTargetPosition=D.Zero(),this.poleTargetLocalOffset=D.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=Pe.Identity(),this._bone1Mat=he.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=D.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const r=t.getParent();if(!r){this._notEnoughInformation=!0,fe.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,this._bone2.children.length===0&&!this._bone2.length){this._notEnoughInformation=!0,fe.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const n=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=Math.PI*.5,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const a=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*a.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*o.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const a=this._bone2.children[0].getAbsolutePosition(e),o=this._bone2.getAbsolutePosition(e),l=this._bone1.getAbsolutePosition(e);this._bone2Length=D.Distance(a,o),this._bone1Length=D.Distance(o,l)}else{e.computeWorldMatrix(!0);const a=this._bone2.getScale();this._bone2Length=this._bone2.length*a.y*this.mesh.scaling.y;const o=this._bone2.getAbsolutePosition(e),l=this._bone1.getAbsolutePosition(e);this._bone1Length=D.Distance(o,l)}this._bone1.getRotationMatrixToRef(1,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||e==null)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Dd._TmpMats[0],r=Dd._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&D.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const n=Dd._TmpVecs[0],a=Dd._TmpVecs[1],o=Dd._TmpVecs[2],l=Dd._TmpVecs[3],c=Dd._TmpVecs[4],u=Dd._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,n),t.subtractToRef(n,c),c.x==0&&c.y==0&&c.z==0?c.y=1:c.normalize(),e.subtractToRef(n,l),l.normalize(),D.CrossToRef(l,c,a),a.normalize(),D.CrossToRef(l,a,o),o.normalize(),he.FromXYZAxesToRef(o,l,a,i);const h=this._bone1Length,d=this._bone2Length;let f=D.Distance(n,e);this._maxReach>0&&(f=Math.min(this._maxReach,f));let p=(d*d+f*f-h*h)/(2*d*f),m=(f*f+h*h-d*d)/(2*f*h);p>1&&(p=1),m>1&&(m=1),p<-1&&(p=-1),m<-1&&(m=-1);const g=Math.acos(p),_=Math.acos(m);let y=-g-_;if(this._rightHandedSystem)he.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),he.RotationAxisToRef(this._bendAxis,_,r),r.multiplyToRef(i,i);else{const v=Dd._TmpVecs[5];v.copyFrom(this._bendAxis),v.x*=-1,he.RotationAxisToRef(v,-_,r),r.multiplyToRef(i,i)}this.poleAngle&&(he.RotationAxisToRef(l,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||Pe.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),Pe.FromRotationMatrixToRef(i,u),Pe.SlerpToRef(this._bone1Quat,u,this.slerpAmount,this._bone1Quat),y=this._bone2Ang*(1-this.slerpAmount)+y*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,1,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,1,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,y,0),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=y}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new Pe),e.getRotationQuaternionToRef(0,null,e._linkedTransformNode.rotationQuaternion))}}Dd._TmpVecs=[D.Zero(),D.Zero(),D.Zero(),D.Zero(),D.Zero(),D.Zero()];Dd._TmpQuat=Pe.Identity();Dd._TmpMats=[he.Identity(),he.Identity()];class Gl{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),this._maxYaw!=null&&(this._midYawConstraint=this._getAngleDiff(this._minYaw,this._maxYaw)*.5+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),this._minYaw!=null&&(this._midYawConstraint=this._getAngleDiff(this._minYaw,this._maxYaw)*.5+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=D.Up(),this.upAxisSpace=0,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=Pe.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=D.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),r.maxYaw!=null?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,r.minYaw!=null?this.minYaw=r.minYaw:this.minYaw=-Math.PI,r.maxPitch!=null?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,r.minPitch!=null?this.minPitch=r.minPitch:this.minPitch=-Math.PI,r.slerpAmount!=null&&(this.slerpAmount=r.slerpAmount),r.upAxis!=null&&(this.upAxis=r.upAxis),r.upAxisSpace!=null&&(this.upAxisSpace=r.upAxisSpace),r.yawAxis!=null||r.pitchAxis!=null){let n=Da.Y,a=Da.X;r.yawAxis!=null&&(n=r.yawAxis.clone(),n.normalize()),r.pitchAxis!=null&&(a=r.pitchAxis.clone(),a.normalize());const o=D.Cross(a,n);this._transformYawPitch=he.Identity(),he.FromXYZAxesToRef(a,n,o,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}r.useAbsoluteValueForYaw!==void 0&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}!t.getParent()&&this.upAxisSpace==2&&(this.upAxisSpace=0)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}const e=this.bone,t=Gl._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const r=Gl._TmpMats[0],n=Gl._TmpMats[1],a=this.mesh,o=e.getParent(),l=Gl._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==2&&o?(this._transformYawPitch&&D.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),o.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==0&&(a.getDirectionToRef(l,l),(a.scaling.x!=1||a.scaling.y!=1||a.scaling.z!=1)&&l.normalize());let c=!1,u=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(c=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(u=!0),c||u){const g=Gl._TmpMats[2],_=Gl._TmpMats[3];if(this.upAxisSpace==2&&l.y==1&&o)o.getRotationMatrixToRef(1,this.mesh,g);else if(this.upAxisSpace==0&&l.y==1&&!o)g.copyFrom(a.getWorldMatrix());else{let v=Gl._TmpVecs[2];v.copyFrom(this._fowardAxis),this._transformYawPitch&&D.TransformCoordinatesToRef(v,this._transformYawPitchInv,v),o?o.getDirectionToRef(v,this.mesh,v):a.getDirectionToRef(v,v);const x=D.Cross(l,v);x.normalize(),v=D.Cross(x,l),he.FromXYZAxesToRef(x,l,v,g)}g.invertToRef(_);let y=null;if(u){const v=Gl._TmpVecs[3];i.subtractToRef(t,v),D.TransformCoordinatesToRef(v,_,v),y=Math.sqrt(v.x*v.x+v.z*v.z);const x=Math.atan2(v.y,y);let A=x;x>this._maxPitch?(v.y=this._maxPitchTan*y,A=this._maxPitch):xthis._maxYaw||AMath.PI?this._isAngleBetween(x,this._maxYaw,this._midYawConstraint)?(v.z=this._maxYawCos*y,v.x=this._maxYawSin*y,b=this._maxYaw):this._isAngleBetween(x,this._midYawConstraint,this._minYaw)&&(v.z=this._minYawCos*y,v.x=this._minYawSin*y,b=this._minYaw):A>this._maxYaw?(v.z=this._maxYawCos*y,v.x=this._maxYawSin*y,x<0&&this.useAbsoluteValueForYaw&&(v.x*=-1),b=this._maxYaw):AMath.PI){const C=Gl._TmpVecs[8];C.copyFrom(Da.Z),this._transformYawPitch&&D.TransformCoordinatesToRef(C,this._transformYawPitchInv,C);const T=Gl._TmpMats[4];this._boneQuat.toRotationMatrix(T),this.mesh.getWorldMatrix().multiplyToRef(T,T),D.TransformCoordinatesToRef(C,T,C),D.TransformCoordinatesToRef(C,_,C);const w=Math.atan2(C.x,C.z),P=this._getAngleBetween(w,x),M=this._getAngleBetween(w,this._midYawConstraint);if(P>M){y==null&&(y=Math.sqrt(v.x*v.x+v.z*v.z));const R=this._getAngleBetween(w,this._maxYaw);this._getAngleBetween(w,this._minYaw)Math.PI?i-=Math.PI*2:i<-Math.PI&&(i+=Math.PI*2),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t;let i=0;return eMath.PI&&(i=Math.PI*2-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,i=i<0?i+2*Math.PI:i,tt&&ei&&e{const s=new Uint8Array(4),e=new Uint32Array(s.buffer);return!!((e[0]=1)&s[0])})();Object.defineProperty($.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty($.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty($.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});$.prototype._rebuild=function(){var s,e;(s=this._buffer)==null||s._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};$.prototype.dispose=function(){var s;this._ownsBuffer&&this._buffer.dispose(),(s=this._alignedBuffer)==null||s.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};$.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};$.prototype._alignBuffer=function(){var h;const s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!s)return;const e=$.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,r=this._maxVerticesCount,a=r*t/e;let o;if(Array.isArray(s)){const d=new Float32Array(s);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else s instanceof ArrayBuffer?o=new DataView(s,0,s.byteLength):o=new DataView(s.buffer,s.byteOffset,s.byteLength);let l;this.type===$.BYTE?l=new Int8Array(a):this.type===$.UNSIGNED_BYTE?l=new Uint8Array(a):this.type===$.SHORT?l=new Int16Array(a):this.type===$.UNSIGNED_SHORT?l=new Uint16Array(a):this.type===$.INT?l=new Int32Array(a):this.type===$.UNSIGNED_INT?l=new Uint32Array(a):l=new Float32Array(a);const c=this.getSize();let u=this.byteOffset;for(let d=0;d{if(t.type!==yt.POINTERWHEEL)return;const i=t.event,r=i.deltaMode===iT.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yt.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}F([X()],yz.prototype,"wheelPrecisionX",void 0);F([X()],yz.prototype,"wheelPrecisionY",void 0);F([X()],yz.prototype,"wheelPrecisionZ",void 0);class BJ{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let r=0,n=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var h,d;const l=o.event,c=l.pointerType==="touch";if(o.type!==yt.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)return;const u=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){const f=l.movementX,p=l.movementY;this.onTouch(null,f,p),this._pointA=null,this._pointB=null}else{if(o.type!==yt.POINTERDOWN&&o.type!==yt.POINTERDOUBLETAP&&c&&((h=this._pointA)==null?void 0:h.pointerId)!==l.pointerId&&((d=this._pointB)==null?void 0:d.pointerId)!==l.pointerId)return;if(o.type===yt.POINTERDOWN&&(this._currentActiveButton===-1||c)){try{u==null||u.setPointerCapture(l.pointerId)}catch{}if(this._pointA===null)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else if(this._pointB===null)this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else return;this._currentActiveButton===-1&&!c&&(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===yt.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===yt.POINTERUP&&(this._currentActiveButton===l.button||c)){try{u==null||u.releasePointerCapture(l.pointerId)}catch{}c||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(r!==0||n)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,n,null),r=0,n=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===yt.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){const f=l.clientX-this._pointA.x,p=l.clientY-this._pointA.y;this._pointA.x=l.clientX,this._pointA.y=l.clientY,this.onTouch(this._pointA,f,p)}else if(this._pointA&&this._pointB){const f=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;f.x=l.clientX,f.y=l.clientY;const p=this._pointA.x-this._pointB.x,m=this._pointA.y-this._pointB.y,g=p*p+m*m,_={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,r,g,n,_),n=_,r=g}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yt.POINTERDOWN|yt.POINTERUP|yt.POINTERMOVE|yt.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,n=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const a=this.camera.getScene().getEngine().getHostWindow();a&&Me.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Me.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,n,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}F([X()],BJ.prototype,"buttons",void 0);var pc={};class xz{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){fe.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=Nt.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const i in this.attached){const r=this.attached[i],n=qe.Serialize(r);t[r.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const r=pc[i];if(r){const n=t[i],a=qe.Parse(()=>new r,n,null);this.add(a)}}}else for(const i in this.attached){const r=pc[this.attached[i].getClassName()];if(r){const n=qe.Parse(()=>new r,e,null);this.remove(this.attached[i]),this.add(n)}}}}class A2t{constructor(e,t){this.x=e,this.y=t}}class hl{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,n=1,a=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=hl.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=n,this._rightStickAxisX=a,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}hl.GAMEPAD=0;hl.GENERIC=1;hl.XBOX=2;hl.POSE_ENABLED=3;hl.DUALSHOCK=4;class G9e extends hl{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new Ae,this.onButtonUpObservable=new Ae,this.type=hl.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{t.type!==hl.POSE_ENABLED&&(!this.gamepad||t.type===hl.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(hl.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(t.x!=0){const r=t.x/this.gamepadRotationSensibility;r!=0&&Math.abs(r)>.005&&(e.inertialAlphaOffset+=r)}if(t.y!=0){const r=t.y/this.gamepadRotationSensibility*this._yAxisScale;r!=0&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}const i=this.gamepad.leftStick;if(i&&i.y!=0){const r=i.y/this.gamepadMoveSensibility;r!=0&&Math.abs(r)>.005&&(this.camera.inertialRadiusOffset-=r)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}F([X()],Az.prototype,"gamepadRotationSensibility",void 0);F([X()],Az.prototype,"gamepadMoveSensibility",void 0);pc.ArcRotateCameraGamepadInput=Az;class P0{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===lg.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?i=r/(1+this.wheelDeltaPercentage):i=r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==yt.POINTERWHEEL)return;const i=t.event;let r=0;const n=i.deltaMode===iT.DOM_DELTA_LINE?b2t:1,a=-(i.deltaY*n);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius),r>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+r;for(let c=0;c<20&&Math.abs(l)>.001;c++)o-=l,l*=this.camera.inertia;o=At.Clamp(o,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,o)}}else r=a/(this.wheelPrecision*40);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yt.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Xl.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,he.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=D.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const l=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/il&&(e=(t.radius-l)*i-t.inertialRadiusOffset)}const n=e/i/t.radius,a=this._getPosition(),o=se.Vector3[6];a.subtractToRef(t.target,o),o.scaleInPlace(n),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(n,a)):this.multiTouchPanning?this._computeMultiTouchPanning(n,a):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Th.MinimumRadiusForPinch=.001;F([X()],Th.prototype,"buttons",void 0);F([X()],Th.prototype,"angularSensibilityX",void 0);F([X()],Th.prototype,"angularSensibilityY",void 0);F([X()],Th.prototype,"pinchPrecision",void 0);F([X()],Th.prototype,"pinchDeltaPercentage",void 0);F([X()],Th.prototype,"useNaturalPinchZoom",void 0);F([X()],Th.prototype,"pinchZoom",void 0);F([X()],Th.prototype,"panningSensibility",void 0);F([X()],Th.prototype,"multiTouchPanning",void 0);F([X()],Th.prototype,"multiTouchPanAndZoom",void 0);pc.ArcRotateCameraPointersInput=Th;class kJ extends xz{constructor(e){super(e)}addMouseWheel(){return this.add(new Jw),this}addPointers(){return this.add(new Th),this}addKeyboard(){return this.add(new P0),this}}kJ.prototype.addVRDeviceOrientation=function(){return this.add(new Mge),this};class Mge{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&(typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(i=>{i==="granted"?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Me.Warn("Permission not granted.")}).catch(i=>{Me.Error(i)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){e.alpha!==null&&(this._alpha=(+e.alpha|0)*this.alphaCorrection),e.gamma!==null&&(this._gamma=(+e.gamma|0)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}pc.ArcRotateCameraVRDeviceOrientationInput=Mge;class i3{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(t.type===lg.KEYDOWN)(this.keysForward.indexOf(i.keyCode)!==-1||this.keysBackward.indexOf(i.keyCode)!==-1||this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysForward.indexOf(i.keyCode)!==-1||this.keysBackward.indexOf(i.keyCode)!==-1||this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(t)},yt.POINTERDOWN|yt.POINTERUP|yt.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,r=this.camera.getEngine();if(!this.touchEnabled&&t.pointerType==="touch"||e.type!==yt.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const n=t.target;if(e.type===yt.POINTERDOWN){try{n==null||n.setPointerCapture(t.pointerId)}catch{}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||t.preventDefault(),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===yt.POINTERUP){try{n==null||n.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===yt.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}const a=t.clientX-this._previousPosition.x,o=t.clientY-this._previousPosition.y;this._rotateCamera(a,o),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const r=e.movementX,n=e.movementY;this._rotateCamera(r,n),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,r=i._calculateHandednessMultiplier();e*=r;const n=e/this.angularSensibility,a=t/this.angularSensibility,o=Pe.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(c=>c===this.activeButton)&&(l=Pe.RotationAxis(Da.X,a),o.multiplyInPlace(l)),this.buttonsYaw.some(c=>c===this.activeButton)){l=Pe.RotationAxis(Da.Y,n),o.multiplyInPlace(l);const c=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-cc===this.activeButton)&&(l=Pe.RotationAxis(Da.Z,-n),i._trackRoll-=n,o.multiplyInPlace(l)),o.toEulerAnglesToRef(i.rotation)}}F([X()],bz.prototype,"buttons",void 0);F([X()],bz.prototype,"angularSensibility",void 0);pc.FlyCameraMouseInput=bz;class Jl{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===lg.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(this.keysHeightOffsetIncr.indexOf(i.keyCode)!==-1||this.keysHeightOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetIncr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRadiusIncr.indexOf(i.keyCode)!==-1||this.keysRadiusDecr.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysHeightOffsetIncr.indexOf(i.keyCode)!==-1||this.keysHeightOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetIncr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRadiusIncr.indexOf(i.keyCode)!==-1||this.keysRadiusDecr.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach(e=>{this.keysHeightOffsetIncr.indexOf(e)!==-1&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:this.keysHeightOffsetDecr.indexOf(e)!==-1&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:this.keysRotationOffsetIncr.indexOf(e)!==-1&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):this.keysRotationOffsetDecr.indexOf(e)!==-1&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):this.keysRadiusIncr.indexOf(e)!==-1&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:this.keysRadiusDecr.indexOf(e)!==-1&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}F([X()],Jl.prototype,"keysHeightOffsetIncr",void 0);F([X()],Jl.prototype,"keysHeightOffsetDecr",void 0);F([X()],Jl.prototype,"keysHeightOffsetModifierAlt",void 0);F([X()],Jl.prototype,"keysHeightOffsetModifierCtrl",void 0);F([X()],Jl.prototype,"keysHeightOffsetModifierShift",void 0);F([X()],Jl.prototype,"keysRotationOffsetIncr",void 0);F([X()],Jl.prototype,"keysRotationOffsetDecr",void 0);F([X()],Jl.prototype,"keysRotationOffsetModifierAlt",void 0);F([X()],Jl.prototype,"keysRotationOffsetModifierCtrl",void 0);F([X()],Jl.prototype,"keysRotationOffsetModifierShift",void 0);F([X()],Jl.prototype,"keysRadiusIncr",void 0);F([X()],Jl.prototype,"keysRadiusDecr",void 0);F([X()],Jl.prototype,"keysRadiusModifierAlt",void 0);F([X()],Jl.prototype,"keysRadiusModifierCtrl",void 0);F([X()],Jl.prototype,"keysRadiusModifierShift",void 0);F([X()],Jl.prototype,"heightSensibility",void 0);F([X()],Jl.prototype,"rotationSensibility",void 0);F([X()],Jl.prototype,"radiusSensibility",void 0);pc.FollowCameraKeyboardMoveInput=Jl;class zx{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==yt.POINTERWHEEL)return;const i=t.event;let r=0;const n=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&fe.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=n*.01*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=n*.01*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=n*.01*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=n*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yt.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}F([X()],zx.prototype,"axisControlRadius",void 0);F([X()],zx.prototype,"axisControlHeight",void 0);F([X()],zx.prototype,"axisControlRotation",void 0);F([X()],zx.prototype,"wheelPrecision",void 0);F([X()],zx.prototype,"wheelDeltaPercentage",void 0);pc.FollowCameraMouseWheelInput=zx;class Mh extends BJ{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,n,a){if(i===0&&n===null||r===0&&a===null)return;let o=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!==0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&fe.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&fe.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&fe.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}F([X()],Mh.prototype,"angularSensibilityX",void 0);F([X()],Mh.prototype,"angularSensibilityY",void 0);F([X()],Mh.prototype,"pinchPrecision",void 0);F([X()],Mh.prototype,"pinchDeltaPercentage",void 0);F([X()],Mh.prototype,"axisXControlRadius",void 0);F([X()],Mh.prototype,"axisXControlHeight",void 0);F([X()],Mh.prototype,"axisXControlRotation",void 0);F([X()],Mh.prototype,"axisYControlRadius",void 0);F([X()],Mh.prototype,"axisYControlHeight",void 0);F([X()],Mh.prototype,"axisYControlRotation",void 0);F([X()],Mh.prototype,"axisPinchControlRadius",void 0);F([X()],Mh.prototype,"axisPinchControlHeight",void 0);F([X()],Mh.prototype,"axisPinchControlRotation",void 0);pc.FollowCameraPointersInput=Mh;class ef{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===lg.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){const r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const n=r.event,a=n.pointerType==="touch";if(!this.touchEnabled&&a||r.type!==yt.POINTERMOVE&&this.buttons.indexOf(n.button)===-1)return;const o=n.target;if(r.type===yt.POINTERDOWN){if(a&&this._activePointerId!==-1||!a&&this._currentActiveButton!==-1)return;this._activePointerId=n.pointerId;try{o==null||o.setPointerCapture(n.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=n.button),this._previousPosition={x:n.clientX,y:n.clientY},e||(n.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===yt.POINTERUP){if(a&&this._activePointerId!==n.pointerId||!a&&this._currentActiveButton!==n.button)return;try{o==null||o.releasePointerCapture(n.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||n.preventDefault(),this._activePointerId=-1}else if(r.type===yt.POINTERMOVE&&(this._activePointerId===n.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){const l=this.camera._calculateHandednessMultiplier(),c=(n.clientX-this._previousPosition.x)*l,u=n.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=c/this.angularSensibility,this.camera.cameraRotation.x+=u/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:c,offsetY:u}),this._previousPosition={x:n.clientX,y:n.clientY},e||n.preventDefault()}}}),this._onMouseMove=r=>{if(!t.isPointerLock)return;const n=this.camera._calculateHandednessMultiplier(),a=r.movementX*n;this.camera.cameraRotation.y+=a/this.angularSensibility;const o=r.movementY;this.camera.cameraRotation.x+=o/this.angularSensibility,this._previousPosition=null,e||r.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yt.POINTERDOWN|yt.POINTERUP|yt.POINTERMOVE),i&&(this._contextMenuBind=r=>this.onContextMenu(r),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}F([X()],Cz.prototype,"buttons",void 0);F([X()],Cz.prototype,"angularSensibility",void 0);pc.FreeCameraMouseInput=Cz;var _n;(function(s){s[s.MoveRelative=0]="MoveRelative",s[s.RotateRelative=1]="RotateRelative",s[s.MoveScene=2]="MoveScene"})(_n||(_n={}));class w0 extends yz{constructor(){super(...arguments),this._moveRelative=D.Zero(),this._rotateRelative=D.Zero(),this._moveScene=D.Zero(),this._wheelXAction=_n.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=_n.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==_n.MoveRelative||(this._wheelXAction=_n.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==_n.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==_n.MoveRelative||(this._wheelYAction=_n.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==_n.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==_n.MoveRelative||(this._wheelZAction=_n.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==_n.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==_n.RotateRelative||(this._wheelXAction=_n.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==_n.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==_n.RotateRelative||(this._wheelYAction=_n.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==_n.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==_n.RotateRelative||(this._wheelZAction=_n.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==_n.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==_n.MoveScene||(this._wheelXAction=_n.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==_n.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==_n.MoveScene||(this._wheelYAction=_n.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==_n.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==_n.MoveScene||(this._wheelZAction=_n.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==_n.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=he.Zero();this.camera.getViewMatrix().invertToRef(e);const t=D.Zero();D.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let r=null;switch(t){case _n.MoveRelative:r=this._moveRelative;break;case _n.RotateRelative:r=this._rotateRelative;break;case _n.MoveScene:r=this._moveScene;break}switch(i){case 0:r.set(e,0,0);break;case 1:r.set(0,e,0);break;case 2:r.set(0,0,e);break}}}F([X()],w0.prototype,"wheelXMoveRelative",null);F([X()],w0.prototype,"wheelYMoveRelative",null);F([X()],w0.prototype,"wheelZMoveRelative",null);F([X()],w0.prototype,"wheelXRotateRelative",null);F([X()],w0.prototype,"wheelYRotateRelative",null);F([X()],w0.prototype,"wheelZRotateRelative",null);F([X()],w0.prototype,"wheelXMoveScene",null);F([X()],w0.prototype,"wheelYMoveScene",null);F([X()],w0.prototype,"wheelZMoveScene",null);pc.FreeCameraMouseWheelInput=w0;class Sz{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Me.IsSafari()}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const r=i.event,n=r.pointerType==="mouse"||this._isSafari&&typeof r.pointerType>"u";if(!(!this.allowMouse&&n)){if(i.type===yt.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),this._pointerPressed.length!==1)return;t={x:r.clientX,y:r.clientY}}else if(i.type===yt.POINTERUP){e||r.preventDefault();const a=this._pointerPressed.indexOf(r.pointerId);if(a===-1||(this._pointerPressed.splice(a,1),a!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===yt.POINTERMOVE){if(e||r.preventDefault(),!t||this._pointerPressed.indexOf(r.pointerId)!=0)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yt.POINTERDOWN|yt.POINTERUP|yt.POINTERMOVE),this._onLostFocus){const r=this.camera.getEngine().getInputElement();r&&r.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const r=e._computeLocalCameraSpeed(),n=new D(0,0,this.touchMoveSensibility!==0?r*this._offsetY/this.touchMoveSensibility:0);he.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(D.TransformCoordinates(n,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}F([X()],Sz.prototype,"touchAngularSensibility",void 0);F([X()],Sz.prototype,"touchMoveSensibility",void 0);pc.FreeCameraTouchInput=Sz;class Ez extends xz{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new ef),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new Cz(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new w0,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Sz),this}clear(){super.clear(),this._mouseInput=null}}Ez.prototype.addDeviceOrientation=function(s){return this._deviceOrientationInput||(this._deviceOrientationInput=new Rge,s&&(this._deviceOrientationInput.smoothFactor=s),this.add(this._deviceOrientationInput)),this};class Rge{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1;const n=()=>{window.removeEventListener("deviceorientation",n),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",n),i("WaitForOrientationChangeAsync timed out"))},e),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(a=>{a=="granted"?window.addEventListener("deviceorientation",n):Me.Warn("Permission not granted.")}).catch(a=>{Me.Error(a)}):window.addEventListener("deviceorientation",n)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new Pe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new Ae,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Me.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=e.alpha!==null?Me.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?Me.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?Me.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=e.alpha!==null?e.alpha:0,this._beta=e.beta!==null?e.beta:0,this._gamma=e.gamma!==null?e.gamma:0),e.alpha!==null&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTransform=new Pe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,this._camera!=null&&!this._camera.rotationQuaternion&&(this._camera.rotationQuaternion=new Pe),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(i=>{i==="granted"?t():Me.Warn("Permission not granted.")}).catch(i=>{Me.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(Pe.RotationYawPitchRollToRef(Me.ToRadians(this._alpha),Me.ToRadians(this._beta),-Me.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTransform),this._camera.getScene().useRightHandedSystem?this._camera.rotationQuaternion.y*=-1:this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}pc.FreeCameraDeviceOrientationInput=Rge;class Tz{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=he.Identity(),this._deltaTransform=D.Zero(),this._vector3=D.Zero(),this._vector2=we.Zero()}get invertYAxis(){return this._yAxisScale!==1}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(t=>{t.type!==hl.POSE_ENABLED&&(!this.gamepad||t.type===hl.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(hl.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;this.gamepadMoveSensibility!==0&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&this.gamepadAngularSensibility!==0?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):he.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const r=e._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(t.x*r,0,-t.y*r),D.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}F([X()],Tz.prototype,"gamepadAngularSensibility",void 0);F([X()],Tz.prototype,"gamepadMoveSensibility",void 0);pc.FreeCameraGamepadInput=Tz;var Fue;(function(s){s[s.X=0]="X",s[s.Y=1]="Y",s[s.Z=2]="Z"})(Fue||(Fue={}));class ri{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...ri._GetDefaultOptions(),...t};if(e?this._leftJoystick=!0:this._leftJoystick=!1,ri._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=0,this._axisTargetedByUpAndDown=1,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new aZ,this.deltaPosition=D.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{ri._VJCanvasWidth=window.innerWidth,ri._VJCanvasHeight=window.innerHeight,ri.Canvas&&(ri.Canvas.width=ri._VJCanvasWidth,ri.Canvas.height=ri._VJCanvasHeight),ri._HalfWidth=ri._VJCanvasWidth/2},!ri.Canvas){window.addEventListener("resize",this._onResize,!1),ri.Canvas=document.createElement("canvas"),ri._VJCanvasWidth=window.innerWidth,ri._VJCanvasHeight=window.innerHeight,ri.Canvas.width=window.innerWidth,ri.Canvas.height=window.innerHeight,ri.Canvas.style.width="100%",ri.Canvas.style.height="100%",ri.Canvas.style.position="absolute",ri.Canvas.style.backgroundColor="transparent",ri.Canvas.style.top="0px",ri.Canvas.style.left="0px",ri.Canvas.style.zIndex="5",ri.Canvas.style.touchAction="none",ri.Canvas.setAttribute("touch-action","none");const r=ri.Canvas.getContext("2d");if(!r)throw new Error("Unable to create canvas for virtual joystick");ri._VJCanvasContext=r,ri._VJCanvasContext.strokeStyle="#ffffff",ri._VJCanvasContext.lineWidth=2,document.body.appendChild(ri.Canvas)}ri._HalfWidth=ri.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&ri._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new we(0,0),this._joystickPreviousPointerPos=new we(0,0),this._joystickPointerStartPos=new we(0,0),this._deltaJoystickVector=new we(0,0),this._onPointerDownHandlerRef=r=>{this._onPointerDown(r)},this._onPointerMoveHandlerRef=r=>{this._onPointerMove(r)},this._onPointerUpHandlerRef=r=>{this._onPointerUp(r)},ri.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),ri.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),ri.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),ri.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),ri.Canvas.addEventListener("contextmenu",r=>{r.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),this._leftJoystick===!0?t=e.clientXri._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):ri._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const a=new we(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),o=a.length();o>this.containerSize&&a.scaleInPlace(this.containerSize/o),this._joystickPointerPos.x=this._joystickPointerStartPos.x+a.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+a.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?ri._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(ri._VJCanvasContext.beginPath(),ri._VJCanvasContext.strokeStyle=this._joystickColor,ri._VJCanvasContext.lineWidth=2,ri._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),ri._VJCanvasContext.stroke(),ri._VJCanvasContext.closePath(),ri._VJCanvasContext.beginPath(),ri._VJCanvasContext.lineWidth=6,ri._VJCanvasContext.strokeStyle=this._joystickColor,ri._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),ri._VJCanvasContext.stroke(),ri._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?ri._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(ri._VJCanvasContext.beginPath(),ri._VJCanvasContext.strokeStyle=this._joystickColor,ri._VJCanvasContext.lineWidth=2,ri._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),ri._VJCanvasContext.stroke(),ri._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(ri._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),ri._VJCanvasContext.beginPath(),ri._VJCanvasContext.fillStyle="white",ri._VJCanvasContext.beginPath(),ri._VJCanvasContext.strokeStyle="red",ri._VJCanvasContext.lineWidth=6,ri._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),ri._VJCanvasContext.stroke(),ri._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){ri.Canvas&&(ri.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),ri.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),ri.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),ri.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(ri.Canvas),ri.Canvas=null),this._released=!0}}ri._GlobalJoystickIndex=0;ri._AlwaysVisibleSticks=0;Ez.prototype.addVirtualJoystick=function(){return this.add(new Ige),this};class Ige{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=he.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=D.TransformCoordinates(new D(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new ri(!0),this._leftjoystick.setAxisForUpDown(2),this._leftjoystick.setAxisForLeftRight(0),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new ri(!1),this._rightjoystick.setAxisForUpDown(0),this._rightjoystick.setAxisForLeftRight(1),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}pc.FreeCameraVirtualJoystickInput=Ige;ns.AddNodeConstructor("TargetCamera",(s,e)=>()=>new pa(s,D.Zero(),e));class pa extends Nt{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=D.Zero(),this._tmpTargetVector=D.Zero(),this.cameraDirection=new D(0,0,0),this.cameraRotation=new we(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new Pe,this.rotation=new D(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=D.Zero(),this._initialFocalDistance=1,this._viewMatrix=he.Zero(),this._camMatrix=he.Zero(),this._cameraTransformMatrix=he.Zero(),this._cameraRotationMatrix=he.Zero(),this._referencePoint=new D(0,0,1),this._transformedReferencePoint=D.Zero(),this._deferredPositionUpdate=new D,this._deferredRotationQuaternionUpdate=new Pe,this._deferredRotationUpdate=new D,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=D.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Pe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=ci),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),he.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&Pe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef(se.Matrix[0]),D.TransformNormalToRef(this.cameraDirection,se.Matrix[0],se.Vector3[0]),this._deferredPositionUpdate.addInPlace(se.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(Pe.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))),t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(a),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ge.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&o&&this.onCollide(o))},this.inputs=new Ez(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Me.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new D(0,0,0),this.cameraRotation=new we(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=D.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=D.Zero(),this._transformedDirection=D.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}F([Pn()],Dl.prototype,"ellipsoid",void 0);F([Pn()],Dl.prototype,"ellipsoidOffset",void 0);F([X()],Dl.prototype,"checkCollisions",void 0);F([X()],Dl.prototype,"applyGravity",void 0);ve("BABYLON.FreeCamera",Dl);ns.AddNodeConstructor("TouchCamera",(s,e)=>()=>new Pge(s,D.Zero(),e));class Pge extends Dl{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}ns.AddNodeConstructor("ArcRotateCamera",(s,e)=>()=>new Kr(s,0,0,1,D.Zero(),e));class Kr extends pa{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new he,this._upToYMatrix=new he,this._upVector=D.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){he.RotationAlignToRef(D.UpReadOnly,this._upVector,this._yToUpMatrix),he.RotationAlignToRef(this._upVector,D.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new tx,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new hh,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new z9e,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,n,a,o=!0){super(e,D.Zero(),a,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=D.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=we.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new he,this.panningAxis=new D(1,1,0),this._transformedDirection=new D,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new Ae,this.checkCollisions=!1,this.collisionRadius=new D(.5,.5,.5),this._previousPosition=D.Zero(),this._collisionVelocity=D.Zero(),this._newPosition=D.Zero(),this._computationVector=D.Zero(),this._onCollisionPositionChange=(l,c,u=null)=>{u?(this.setPosition(c),this.onCollide&&this.onCollide(u)):this._previousPosition.copyFrom(this._position);const h=Math.cos(this.alpha),d=Math.sin(this.alpha),f=Math.cos(this.beta);let p=Math.sin(this.beta);p===0&&(p=1e-4);const m=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*h*p,this.radius*f,this.radius*d*p),m.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let g=this.upVector;this.allowUpsideDown&&this.beta<0&&(g=g.clone(),g=g.negate()),this._computeViewMatrix(this._position,m,g),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=D.Zero(),n&&this.setTarget(n),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new kJ(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=we.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>ci&&this.restoreStateInterpolationFactor<1?(this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):super._restoreStateValues()?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1}_isSynchronizedViewMatrix(){return super._isSynchronizedViewMatrix()?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1}attachControl(e,t,i=!0,r=2){const n=arguments;t=Me.BackCompatCameraNoPreventDefault(n),this._useCtrlForPanning=i,this._panningMouseButton=r,typeof n[0]=="boolean"&&(n.length>1&&(this._useCtrlForPanning=n[1]),n.length>2&&(this._panningMouseButton=n[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(D.Lerp(this.getTarget(),this._storedTarget,t)),Pe.RotationAlphaBetaGammaToRef(this._storedAlpha,this._storedBeta,0,se.Quaternion[0]),Pe.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,se.Quaternion[1]),Pe.SlerpToRef(se.Quaternion[1],se.Quaternion[0],t,se.Quaternion[2]),se.Quaternion[2].normalize(),se.Quaternion[2].toAlphaBetaGammaToRef(se.Vector3[0]),this.alpha=se.Vector3[0].x,this.beta=se.Vector3[0].y,this.radius+=(this._storedRadius-this.radius)*t,we.LerpToRef(this.targetScreenOffset,this._storedTargetScreenOffset,t,this.targetScreenOffset),(D.DistanceSquared(this.getTarget(),this._storedTarget)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&D.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);const e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){if(r=this.overrideCloneAlphaBetaRadius??r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const n=e,a=this._getTargetPosition();if(a&&!i&&a.equals(n))return;this._targetHost=null,this._target=n,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let r=Math.sin(this.beta);r===0&&(r=1e-4),this.radius===0&&(this.radius=1e-4);const n=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&D.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),n.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const a=this.getScene().collisionCoordinator;this._collider||(this._collider=a.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,a.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let a=this.upVector;this.allowUpsideDown&&r<0&&(a=a.negate()),this._computeViewMatrix(this._position,n,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=n,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Ee.MinMax(e);let r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(e.min===void 0){const n=e||this.getScene().meshes;i=Ee.MinMax(n),r=D.Distance(i.min,i.max)}else{const n=e;i=n,r=n.distance}this._target=Ee.Center(i),t||(this.maxZ=r*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Nt.RIG_MODE_STEREOSCOPIC_INTERLACED:case Nt.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const r=new Kr(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Nt.RIG_MODE_STEREOSCOPIC_INTERLACED:case Nt.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const r=D.Distance(e,t),a=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*a,u=r*.5*i,h=u*Math.sqrt(1+1/(l*l)),d=u*Math.sqrt(1+1/(o*o));return Math.max(h,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}F([X()],Kr.prototype,"alpha",void 0);F([X()],Kr.prototype,"beta",void 0);F([X()],Kr.prototype,"radius",void 0);F([X()],Kr.prototype,"overrideCloneAlphaBetaRadius",void 0);F([Pn("target")],Kr.prototype,"_target",void 0);F([Hw("targetHost")],Kr.prototype,"_targetHost",void 0);F([X()],Kr.prototype,"inertialAlphaOffset",void 0);F([X()],Kr.prototype,"inertialBetaOffset",void 0);F([X()],Kr.prototype,"inertialRadiusOffset",void 0);F([X()],Kr.prototype,"lowerAlphaLimit",void 0);F([X()],Kr.prototype,"upperAlphaLimit",void 0);F([X()],Kr.prototype,"lowerBetaLimit",void 0);F([X()],Kr.prototype,"upperBetaLimit",void 0);F([X()],Kr.prototype,"lowerRadiusLimit",void 0);F([X()],Kr.prototype,"upperRadiusLimit",void 0);F([X()],Kr.prototype,"inertialPanningX",void 0);F([X()],Kr.prototype,"inertialPanningY",void 0);F([X()],Kr.prototype,"pinchToPanMaxDistance",void 0);F([X()],Kr.prototype,"panningDistanceLimit",void 0);F([Pn()],Kr.prototype,"panningOriginTarget",void 0);F([X()],Kr.prototype,"panningInertia",void 0);F([X()],Kr.prototype,"zoomToMouseLocation",null);F([X()],Kr.prototype,"zoomOnFactor",void 0);F([nz()],Kr.prototype,"targetScreenOffset",void 0);F([X()],Kr.prototype,"allowUpsideDown",void 0);F([X()],Kr.prototype,"useInputToRestoreState",void 0);F([X()],Kr.prototype,"restoreStateInterpolationFactor",void 0);ve("BABYLON.ArcRotateCamera",Kr);ns.AddNodeConstructor("DeviceOrientationCamera",(s,e)=>()=>new UJ(s,D.Zero(),e));class UJ extends Dl{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new Pe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new Pe,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(r=>{this._dragFactor!=0&&(this._initialQuaternion||(this._initialQuaternion=new Pe),Pe.FromEulerAnglesToRef(0,r.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=Da.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new Pe),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class W9e extends xz{constructor(e){super(e)}addKeyboard(){return this.add(new i3),this}addMouse(){return this.add(new bz),this}}class eD extends pa{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new D(1,1,1),this.ellipsoidOffset=new D(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=D.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=D.Zero(),this._diffPosition=D.Zero(),this._newPosition=D.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(n,a,o=null)=>{(c=>{this._newPosition.copyFrom(c),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ge.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&o&&this.onCollide(o))})(a)},this.inputs=new W9e(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Me.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new D(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=D.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=D.Zero(),this._transformedDirection=D.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=this.rotation.z,r=t-i,n=.001;Math.abs(r)>=n&&(this.rotation.z+=r/e,Math.abs(t-this.rotation.z)<=n&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}F([Pn()],eD.prototype,"ellipsoid",void 0);F([Pn()],eD.prototype,"ellipsoidOffset",void 0);F([X()],eD.prototype,"checkCollisions",void 0);F([X()],eD.prototype,"applyGravity",void 0);ve("BABYLON.FlyCamera",eD);class K9e extends xz{constructor(e){super(e)}addKeyboard(){return this.add(new Jl),this}addMouseWheel(){return this.add(new zx),this}addPointers(){return this.add(new Mh),this}addVRDeviceOrientation(){return fe.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}ns.AddNodeConstructor("FollowCamera",(s,e)=>()=>new au(s,D.Zero(),e));ns.AddNodeConstructor("ArcFollowCamera",(s,e)=>()=>new wge(s,0,0,1,null,e));class au extends pa{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new K9e(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=se.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),r=Me.ToRadians(this.rotationOffset)+i,n=e.getAbsolutePosition(),a=n.x+Math.sin(r)*this.radius,o=n.z+Math.cos(r)*this.radius,l=a-this.position.x,c=n.y+this.heightOffset-this.position.y,u=o-this.position.z;let h=l*this.cameraAcceleration*2,d=c*this.cameraAcceleration,f=u*this.cameraAcceleration*2;(h>this.maxCameraSpeed||h<-this.maxCameraSpeed)&&(h=h<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new D(this.position.x+h,this.position.y+d,this.position.z+f),this.setTarget(n)}attachControl(e,t){t=Me.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),this.lowerHeightOffsetLimit!==null&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),this.lowerRotationOffsetLimit!==null&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}F([X()],au.prototype,"radius",void 0);F([X()],au.prototype,"lowerRadiusLimit",void 0);F([X()],au.prototype,"upperRadiusLimit",void 0);F([X()],au.prototype,"rotationOffset",void 0);F([X()],au.prototype,"lowerRotationOffsetLimit",void 0);F([X()],au.prototype,"upperRotationOffsetLimit",void 0);F([X()],au.prototype,"heightOffset",void 0);F([X()],au.prototype,"lowerHeightOffsetLimit",void 0);F([X()],au.prototype,"upperHeightOffsetLimit",void 0);F([X()],au.prototype,"cameraAcceleration",void 0);F([X()],au.prototype,"maxCameraSpeed",void 0);F([Hw("lockedTargetId")],au.prototype,"lockedTarget",void 0);class wge extends pa{constructor(e,t,i,r,n,a){super(e,D.Zero(),a),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=D.Zero(),this.setMeshTarget(n)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}ve("BABYLON.FollowCamera",au);ve("BABYLON.ArcFollowCamera",wge);var Bue;(function(s){s[s.A=0]="A",s[s.B=1]="B",s[s.X=2]="X",s[s.Y=3]="Y",s[s.LB=4]="LB",s[s.RB=5]="RB",s[s.Back=8]="Back",s[s.Start=9]="Start",s[s.LeftStick=10]="LeftStick",s[s.RightStick=11]="RightStick"})(Bue||(Bue={}));var kue;(function(s){s[s.Up=12]="Up",s[s.Down=13]="Down",s[s.Left=14]="Left",s[s.Right=15]="Right"})(kue||(kue={}));class H9e extends hl{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new Ae,this.onButtonUpObservable=new Ae,this.onPadDownObservable=new Ae,this.onPadUpObservable=new Ae,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=hl.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,0)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,1)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,2)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,3)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,9)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,8)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,4)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,5)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,10)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,11)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,12)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,13)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,14)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,15)}update(){super.update(),this._isXboxOnePad?(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value):(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}var Uue;(function(s){s[s.Cross=0]="Cross",s[s.Circle=1]="Circle",s[s.Square=2]="Square",s[s.Triangle=3]="Triangle",s[s.L1=4]="L1",s[s.R1=5]="R1",s[s.Share=8]="Share",s[s.Options=9]="Options",s[s.LeftStick=10]="LeftStick",s[s.RightStick=11]="RightStick"})(Uue||(Uue={}));var zue;(function(s){s[s.Up=12]="Up",s[s.Down=13]="Down",s[s.Left=14]="Left",s[s.Right=15]="Right"})(zue||(zue={}));class j9e extends hl{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new Ae,this.onButtonUpObservable=new Ae,this.onPadDownObservable=new Ae,this.onPadUpObservable=new Ae,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=hl.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,0)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,1)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,2)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,3)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,9)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,8)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,4)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,5)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,10)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,11)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,12)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,13)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,14)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,15)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class X9e{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new Ae,To()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new Ae(t=>{for(const i in this._babylonGamepads){const r=this._babylonGamepads[i];r&&r._isConnected&&this.onGamepadConnectedObservable.notifyObserver(t,r)}}),this._onGamepadConnectedEvent=t=>{const i=t.gamepad;if(i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected)return;let r;this._babylonGamepads[i.index]?(r=this._babylonGamepads[i.index],r.browserGamepad=i,r._isConnected=!0):r=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(r),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=t=>{const i=t.gamepad;for(const r in this._babylonGamepads)if(this._babylonGamepads[r].index===i.index){const n=this._babylonGamepads[r];n._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(n),n.dispose&&n.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const t=this._scene?this._scene.getEngine().getHostWindow():window;t&&(t.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),t.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=hl.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){this._oneGamepadConnected||(this._oneGamepadConnected=!0);let t;const i=e.id.search("054c")!==-1&&e.id.search("0ce6")===-1,r=e.id.search("Xbox One")!==-1;return r||e.id.search("Xbox 360")!==-1||e.id.search("xinput")!==-1||e.id.search("045e")!==-1&&e.id.search("Surface Dock")===-1?t=new H9e(e.id,e.index,e,r):i?t=new j9e(e.id,e.index,e):t=new G9e(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(!(!t||!t.isConnected))try{t.update()}catch{this._loggedErrors.indexOf(t.index)===-1&&(Me.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&Ge.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new Vx(s,D.Zero(),e));class Vx extends Pge{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}Nt._CreateDefaultParsedCamera=(s,e)=>new Vx(s,D.Zero(),e);ns.AddNodeConstructor("GamepadCamera",(s,e)=>()=>new zJ(s,D.Zero(),e));class zJ extends Vx{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const Q9e="postprocessVertexShader",$9e=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[Q9e]=$9e;const Z9e={name:Q9e,shader:$9e},C2t=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShader:Z9e},Symbol.toStringTag,{value:"Module"}));class Mz{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){var e;return((e=this._textures)==null?void 0:e[0])??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,n){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=n}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,n=14,a){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=a,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:n,label:a},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,r,n,a;let e=null;if(this._isMulti){const o=this.textures;if(o&&o.length>0){let l=!1,c=o.length,u=-1;const h=o[o.length-1]._source;(h===14||h===12)&&(l=!0,u=o[o.length-1].format,c--);const d=[],f=[],p=[],m=[],g=[],_=[],y=[],v={};for(let b=0;b1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e;if(this._textures)for(let t=0;t<((e=this._textures)==null?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)==null||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class S2t extends Mz{constructor(e,t,i,r,n){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=n}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,n=14,a){if(this._depthStencilBuffer){const o=this._engine,l=o._currentFramebuffer,c=this._context;o._bindUnboundFramebuffer(this._framebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_STENCIL_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.STENCIL_ATTACHMENT,c.RENDERBUFFER,null),o._bindUnboundFramebuffer(l),c.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,r,n,a)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer,n=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const a=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;n._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),n._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var l,c;if(!e._hardwareTexture)return;const n=this._framebuffer,a=this._engine,o=a._currentFramebuffer;if(a._bindUnboundFramebuffer(n),a.webGLVersion>1){const u=this._context,h=u["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??((l=this.layerIndices)==null?void 0:l[t])??0,u.framebufferTextureLayer(u.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=i??((c=this.faceIndices)==null?void 0:c[t])??0,u.framebufferTexture2D(u.FRAMEBUFFER,h,u.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):u.framebufferTexture2D(u.FRAMEBUFFER,h,u.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{const u=this._context,h=u["COLOR_ATTACHMENT"+t+"_WEBGL"],d=i!==void 0?u.TEXTURE_CUBE_MAP_POSITIVE_X+i:u.TEXTURE_2D;u.framebufferTexture2D(u.FRAMEBUFFER,h,d,e._hardwareTexture.underlyingResource,r)}a._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=((r=this._attachments)==null?void 0:r.length)??this.textures.length;for(let n=0;n1&&(a.format===15?h=t.DEPTH_COMPONENT16:a.format===16?h=t.DEPTH_COMPONENT24:a.format===17||a.format===13?h=t.DEPTH24_STENCIL8:a.format===14?h=t.DEPTH_COMPONENT32F:a.format===18&&(h=t.DEPTH32F_STENCIL8)),a.is2DArray?t.texImage3D(n,0,h,a.width,a.height,i,0,u,c,null):a.is3D?t.texImage3D(n,0,h,a.width,a.height,r,0,u,c,null):t.texImage2D(n,0,h,a.width,a.height,0,u,c,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),a};bi.prototype.updateRenderTargetTextureSampleCount=function(s,e){if(this.webGLVersion<2||!s||!s.texture)return 1;if(s.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),s._depthStencilBuffer&&(t.deleteRenderbuffer(s._depthStencilBuffer),s._depthStencilBuffer=null),s._MSAAFramebuffer&&(t.deleteFramebuffer(s._MSAAFramebuffer),s._MSAAFramebuffer=null);const i=s.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const r=t.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");s._MSAAFramebuffer=r,this._bindUnboundFramebuffer(s._MSAAFramebuffer);const n=this._createRenderBuffer(s.texture.width,s.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(s.texture.type,s.texture.format,s.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(s._framebuffer);return s.texture.samples=e,s._samples=e,s._depthStencilBuffer=this._setupFramebufferDepthAttachments(s._generateStencilBuffer,s._generateDepthBuffer,s.texture.width,s.texture.height,e),this._bindUnboundFramebuffer(null),e};bi.prototype._setupDepthStencilTexture=function(s,e,t,i,r,n=1){const a=e.width||e,o=e.height||e,l=e.layers||0,c=e.depth||0;s.baseWidth=a,s.baseHeight=o,s.width=a,s.height=o,s.is2DArray=l>0,s.depth=l||c,s.isReady=!0,s.samples=n,s.generateMipMaps=!1,s.samplingMode=i?2:1,s.type=0,s._comparisonFunction=r;const u=this._gl,h=this._getTextureTarget(s),d=this._getSamplingParameters(s.samplingMode,!1);u.texParameteri(h,u.TEXTURE_MAG_FILTER,d.mag),u.texParameteri(h,u.TEXTURE_MIN_FILTER,d.min),u.texParameteri(h,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(h,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),this.webGLVersion>1&&(r===0?(u.texParameteri(h,u.TEXTURE_COMPARE_FUNC,515),u.texParameteri(h,u.TEXTURE_COMPARE_MODE,u.NONE)):(u.texParameteri(h,u.TEXTURE_COMPARE_FUNC,r),u.texParameteri(h,u.TEXTURE_COMPARE_MODE,u.COMPARE_REF_TO_TEXTURE)))};Ge.prototype.setTextureFromPostProcess=function(s,e,t){let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(s,(i==null?void 0:i.texture)??null,t)};Ge.prototype.setTextureFromPostProcessOutput=function(s,e,t){var i;this._bindTexture(s,((i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)??null,t)};zi.prototype.setTextureFromPostProcess=function(s,e){this._engine.setTextureFromPostProcess(this._samplers[s],e,s)};zi.prototype.setTextureFromPostProcessOutput=function(s,e){this._engine.setTextureFromPostProcessOutput(this._samplers[s],e,s)};class Ft{static RegisterShaderCodeProcessing(e,t){if(!t){delete Ft._CustomShaderCodeProcessing[e??""];return}Ft._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){return Ft._CustomShaderCodeProcessing[e]??Ft._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,n,a,o=1,l,c,u=null,h=0,d="postprocess",f,p=!1,m=5,g,_){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._shadersLoaded=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new no(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new we(1,1),this._texelSize=we.Zero(),this.onEffectCreatedObservable=new Ae(void 0,!0),this.onActivateObservable=new Ae,this.onSizeChangedObservable=new Ae,this.onApplyObservable=new Ae,this.onBeforeRenderObservable=new Ae,this.onAfterRenderObservable=new Ae,this._importPromises=[],this.name=e;let y=1,v=null;if(i&&!Array.isArray(i)){const x=i;i=x.uniforms??null,r=x.samplers??null,y=x.size??1,a=x.camera??null,o=x.samplingMode??1,l=x.engine,c=x.reusable,u=x.defines??null,h=x.textureType??0,d=x.vertexUrl??"postprocess",f=x.indexParameters,p=x.blockCompilation??!1,m=x.textureFormat??5,g=x.shaderLanguage??0,v=x.uniformBuffers??null}else n&&(typeof n=="number"?y=n:y={width:n.width,height:n.height});a!=null?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=y,this.renderTargetSamplingMode=o||1,this._reusable=c||!1,this._textureType=h,this._textureFormat=m,this._shaderLanguage=g||0,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=v||[],this._indexParameters=f,this._drawWrapper=new Ro(this._engine),this._webGPUReady=this._shaderLanguage===1,this._postConstructor(p,u,_)}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>vRt),void 0)])):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>C2t),void 0)]))}_postConstructor(e,t=null,i){const n=this.getEngine().isWebGPU&&!Ft.ForceGLSL;this._gatherImports(n,this._importPromises),i&&i(n,this._importPromises),n&&this._webGPUReady&&(this._shaderLanguage=1),e||this.updateEffect(t)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new no(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,n,a,o,l){const c=Ft._GetShaderCodeProcessing(this.name);if(c!=null&&c.defineCustomBindings){const u=(t==null?void 0:t.slice())??[];u.push(...this._parameters);const h=(i==null?void 0:i.slice())??[];h.push(...this._samplers),e=c.defineCustomBindings(this.name,e,u,h),t=u,i=h}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:l??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:n??null,onError:a??null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:c!=null&&c.processCodeAfterIncludes?(u,h)=>c.processCodeAfterIncludes(this.name,u,h):null,processFinalCode:c!=null&&c.processFinalCode?(u,h)=>c.processFinalCode(this.name,u,h):null,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0}},this._engine),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let n=0;n=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let r=0;r0&&this._textures.reset(),this.width=e,this.height=t;let a=null;if(i){for(let c=0;c{m.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(m,this.samples)}),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/c,l/u),this._engine.bindFramebuffer(d,0,o,l,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),(p=(f=this._engine)._debugInsertMarker)==null||p.call(f,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e;return((e=this._drawWrapper.effect)==null?void 0:e.isReady())??!1}apply(){var t,i,r;if(!((t=this._drawWrapper.effect)!=null&&t.isReady()))return null;this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),(r=(i=Ft._GetShaderCodeProcessing(this.name))==null?void 0:i.bindCustomBindings)==null||r.call(i,this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._disposeTextures();let t;if(this._scene&&(t=this._scene.postProcesses.indexOf(this),t!==-1&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const i=this._parentContainer.postProcesses.indexOf(this);i>-1&&this._parentContainer.postProcesses.splice(i,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){const i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=qe.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Ft.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const r=Xn(e.customType);if(!r||!r._Parse)return null;const n=t?t.getCameraById(e.cameraId):null;return r._Parse(e,n,t,i)}static _Parse(e,t,i,r){return qe.Parse(()=>new Ft(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}}Ft.ForceGLSL=!1;Ft._CustomShaderCodeProcessing={};F([X()],Ft.prototype,"uniqueId",void 0);F([X()],Ft.prototype,"name",void 0);F([X()],Ft.prototype,"width",void 0);F([X()],Ft.prototype,"height",void 0);F([X()],Ft.prototype,"renderTargetSamplingMode",void 0);F([jw()],Ft.prototype,"clearColor",void 0);F([X()],Ft.prototype,"autoClear",void 0);F([X()],Ft.prototype,"forceAutoClearInAlphaMode",void 0);F([X()],Ft.prototype,"alphaMode",void 0);F([X()],Ft.prototype,"alphaConstants",void 0);F([X()],Ft.prototype,"enablePixelPerfectMode",void 0);F([X()],Ft.prototype,"forceFullscreenViewport",void 0);F([X()],Ft.prototype,"scaleMode",void 0);F([X()],Ft.prototype,"alwaysForcePOT",void 0);F([X("samples")],Ft.prototype,"_samples",void 0);F([X()],Ft.prototype,"adaptScaleToCurrentViewport",void 0);ve("BABYLON.PostProcess",Ft);class D0 extends Ft{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,n,a,o=0,l=!1){super(e,"pass",null,null,t,i,r,n,a,void 0,o,void 0,null,l)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>zRt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>D2t),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new D0(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}ve("BABYLON.PassPostProcess",D0);class Dge extends Ft{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,n,a,o=0,l=!1){super(e,"passCube",null,null,t,i,r,n,a,"#define POSITIVEX",o,void 0,null,l),this._face=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>VRt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>URt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new Dge(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}Ge._RescalePostProcessFactory=s=>new D0("rescale",1,null,2,s,!1,0);class Lge extends Ft{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,n,a){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,n,a),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("leftSampler",this._passedProcess)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>hIt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>uIt),void 0)),super._gatherImports(e,t)}}ve("BABYLON.AnaglyphPostProcess",Lge);function Rz(s){s._rigCameras[0]._rigPostProcess=new D0(s.name+"_passthru",1,s._rigCameras[0]),s._rigCameras[1]._rigPostProcess=new Lge(s.name+"_anaglyph",1,s._rigCameras)}ns.AddNodeConstructor("AnaglyphArcRotateCamera",(s,e,t)=>()=>new q9e(s,0,0,1,D.Zero(),t.interaxial_distance,e));class q9e extends Kr{constructor(e,t,i,r,n,a,o){super(e,t,i,r,n,o),this._setRigMode=()=>Rz(this),this.interaxialDistance=a,this.setCameraRigMode(Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}getClassName(){return"AnaglyphArcRotateCamera"}}ns.AddNodeConstructor("AnaglyphFreeCamera",(s,e,t)=>()=>new J9e(s,D.Zero(),t.interaxial_distance,e));class J9e extends Dl{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>Rz(this),this.interaxialDistance=i,this.setCameraRigMode(Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}ns.AddNodeConstructor("AnaglyphGamepadCamera",(s,e,t)=>()=>new eBe(s,D.Zero(),t.interaxial_distance,e));class eBe extends zJ{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>Rz(this),this.interaxialDistance=i,this.setCameraRigMode(Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}ns.AddNodeConstructor("AnaglyphUniversalCamera",(s,e,t)=>()=>new tBe(s,D.Zero(),t.interaxial_distance,e));class tBe extends Vx{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>Rz(this),this.interaxialDistance=i,this.setCameraRigMode(Nt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const E2t="stereoscopicInterlacePixelShader",T2t=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; #ifdef IS_STEREOSCOPIC_HORIZ useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); #else #ifdef IS_STEREOSCOPIC_INTERLACED float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); #else useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); #endif #endif if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} `;de.ShadersStore[E2t]=T2t;class iBe extends Ft{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,n,a,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],n,a,o,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new we(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new we(1/this.width,1/this.height)}),this.onApplyObservable.add(l=>{l.setTextureFromPostProcess("camASampler",this._passedProcess),l.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}class M2t extends Ft{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,r,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,a,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new we(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new we(1/this.width,1/this.height)}),this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("camASampler",this._passedProcess),o.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}function Iz(s){const e=s.cameraRigMode===Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||s.cameraRigMode===Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=s.cameraRigMode===Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;s.cameraRigMode===Nt.RIG_MODE_STEREOSCOPIC_INTERLACED?(s._rigCameras[0]._rigPostProcess=new D0(s.name+"_passthru",1,s._rigCameras[0]),s._rigCameras[1]._rigPostProcess=new iBe(s.name+"_stereoInterlace",s._rigCameras,!1,!0)):(s._rigCameras[t?1:0].viewport=new uc(0,0,e?.5:1,e?1:.5),s._rigCameras[t?0:1].viewport=new uc(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}ns.AddNodeConstructor("StereoscopicArcRotateCamera",(s,e,t)=>()=>new rBe(s,0,0,1,D.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class rBe extends Kr{constructor(e,t,i,r,n,a,o,l){super(e,t,i,r,n,l),this._setRigMode=()=>Iz(this),this.interaxialDistance=a,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}getClassName(){return"StereoscopicArcRotateCamera"}}ns.AddNodeConstructor("StereoscopicFreeCamera",(s,e,t)=>()=>new sBe(s,D.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class sBe extends Dl{constructor(e,t,i,r,n){super(e,t,n),this._setRigMode=()=>Iz(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}ns.AddNodeConstructor("StereoscopicGamepadCamera",(s,e,t)=>()=>new nBe(s,D.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class nBe extends zJ{constructor(e,t,i,r,n){super(e,t,n),this._setRigMode=()=>Iz(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}ns.AddNodeConstructor("StereoscopicFreeCamera",(s,e,t)=>()=>new aBe(s,D.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class aBe extends Vx{constructor(e,t,i,r,n){super(e,t,n),this._setRigMode=()=>Iz(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Nt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class R2t extends Vx{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,r=1,n=.065){super(e,t,i),this._distanceBetweenEyes=n,this._distanceToProjectionPlane=r,this.setCameraRigMode(Nt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=n}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new pa(e,D.Zero(),this.getScene()),i=new _t("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(he.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new oBe(s,D.Zero(),e));class oBe extends Dl{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class nT{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return he.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return he.Translation(-t,0,0)}get leftPreViewMatrix(){return he.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return he.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new nT;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}class Vue extends Ft{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,xe.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new we(2,2/this.aspectRatio),this._scaleFactor=new we(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new we(this._isRightEye?.5-this._lensCenterOffset*.5:.5+this._lensCenterOffset*.5,.5)}),this.onApplyObservable.add(n=>{n.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),n.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),n.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),n.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>WRt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>GRt),void 0)),super._gatherImports(e,t)}}const I2t="vrMultiviewToSingleviewPixelShader",P2t=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;de.ShadersStore[I2t]=P2t;class Oge{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new lBe(e)}sampleFrame(e=Or.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return e===0?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class lBe{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}bi.prototype.setAlphaMode=function(s,e=!1){if(this._alphaMode===s){if(!e){const t=s===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(s){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break}e||(this.depthCullingState.depthMask=s===0),this._alphaMode=s};bi.prototype.updateDynamicIndexBuffer=function(s,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(s);let i;s.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};bi.prototype.updateDynamicVertexBuffer=function(s,e,t,i){this.bindArrayBuffer(s),t===void 0&&(t=0);const r=e.byteLength||e.length;i===void 0||i>=r&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(e).subarray(t,t+i)):(e instanceof ArrayBuffer?e=new Uint8Array(e,t,i):e=new Uint8Array(e.buffer,e.byteOffset+t,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)),this._resetVertexBufferBinding()};Ge.prototype.displayLoadingUI=function(){if(!To())return;const s=this.loadingScreen;s&&s.displayLoadingUI()};Ge.prototype.hideLoadingUI=function(){if(!To())return;const s=this._loadingScreen;s&&s.hideLoadingUI()};Object.defineProperty(Ge.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Ge.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(s){this._loadingScreen=s},enumerable:!0,configurable:!0});Object.defineProperty(Ge.prototype,"loadingUIText",{set:function(s){this.loadingScreen.loadingUIText=s},enumerable:!0,configurable:!0});Object.defineProperty(Ge.prototype,"loadingUIBackgroundColor",{set:function(s){this.loadingScreen.loadingUIBackgroundColor=s},enumerable:!0,configurable:!0});Ge.prototype.getInputElement=function(){return this._renderingCanvas};Ge.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};Ge.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};Ge.prototype.getAspectRatio=function(s,e=!1){const t=s.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};Ge.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};Ge.prototype._verifyPointerLock=function(){var s;(s=this._onPointerLockChange)==null||s.call(this)};Ge.prototype.setAlphaEquation=function(s){if(this._alphaEquation!==s){switch(s){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774);break}this._alphaEquation=s}};Ge.prototype.getInputElement=function(){return this._renderingCanvas};Ge.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};Ge.prototype.setDepthFunction=function(s){this._depthCullingState.depthFunc=s};Ge.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};Ge.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};Ge.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};Ge.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};Ge.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};Ge.prototype.setDepthWrite=function(s){this._depthCullingState.depthMask=s};Ge.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};Ge.prototype.setStencilBuffer=function(s){this._stencilState.stencilTest=s};Ge.prototype.getStencilMask=function(){return this._stencilState.stencilMask};Ge.prototype.setStencilMask=function(s){this._stencilState.stencilMask=s};Ge.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};Ge.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};Ge.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};Ge.prototype.setStencilFunction=function(s){this._stencilState.stencilFunc=s};Ge.prototype.setStencilFunctionReference=function(s){this._stencilState.stencilFuncRef=s};Ge.prototype.setStencilFunctionMask=function(s){this._stencilState.stencilFuncMask=s};Ge.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};Ge.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};Ge.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};Ge.prototype.setStencilOperationFail=function(s){this._stencilState.stencilOpStencilFail=s};Ge.prototype.setStencilOperationDepthFail=function(s){this._stencilState.stencilOpDepthFail=s};Ge.prototype.setStencilOperationPass=function(s){this._stencilState.stencilOpStencilDepthPass=s};Ge.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()};Ge.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)};Ge.prototype.setAlphaConstants=function(s,e,t,i){this._alphaState.setAlphaBlendConstants(s,e,t,i)};Ge.prototype.getAlphaMode=function(){return this._alphaMode};Ge.prototype.getAlphaEquation=function(){return this._alphaEquation};Ge.prototype.getRenderPassNames=function(){return this._renderPassNames};Ge.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};Ge.prototype.createRenderPassId=function(s){const e=++Ge._RenderPassIdCounter;return this._renderPassNames[e]=s??"NONAME",e};Ge.prototype.releaseRenderPassId=function(s){this._renderPassNames[s]=void 0;for(let e=0;e{s.onCanvasFocusObservable.notifyObservers(s)},s._onCanvasBlur=()=>{s.onCanvasBlurObservable.notifyObservers(s)},s._onCanvasContextMenu=r=>{s.disableContextMenu&&r.preventDefault()},e.addEventListener("focus",s._onCanvasFocus),e.addEventListener("blur",s._onCanvasBlur),e.addEventListener("contextmenu",s._onCanvasContextMenu),s._onBlur=()=>{s.disablePerformanceMonitorInBackground&&s.performanceMonitor.disable(),s._windowIsBackground=!0},s._onFocus=()=>{s.disablePerformanceMonitorInBackground&&s.performanceMonitor.enable(),s._windowIsBackground=!1},s._onCanvasPointerOut=r=>{document.elementFromPoint(r.clientX,r.clientY)!==e&&s.onCanvasPointerOutObservable.notifyObservers(r)};const i=s.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",s._onBlur),i.addEventListener("focus",s._onFocus)),e.addEventListener("pointerout",s._onCanvasPointerOut),t.doNotHandleTouchAction||w2t(e),!Ge.audioEngine&&t.audioEngine&&Ge.AudioEngineFactory&&(Ge.audioEngine=Ge.AudioEngineFactory(s.getRenderingCanvas(),s.getAudioContext(),s.getAudioDestination())),MS()&&(s._onFullscreenChange=()=>{s.isFullscreen=!!document.fullscreenElement,s.isFullscreen&&s._pointerLockRequested&&e&&VJ(e)},document.addEventListener("fullscreenchange",s._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",s._onFullscreenChange,!1),s._onPointerLockChange=()=>{s.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",s._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",s._onPointerLockChange,!1)),s.enableOfflineSupport=Ge.OfflineProviderFactory!==void 0,s._deterministicLockstep=!!t.deterministicLockstep,s._lockstepMaxSteps=t.lockstepMaxSteps||0,s._timeStep=t.timeStep||1/60}function Fge(s,e){Rt.Instances.length===1&&Ge.audioEngine&&(Ge.audioEngine.dispose(),Ge.audioEngine=null);const t=s.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",s._onBlur),t.removeEventListener("focus",s._onFocus)),e&&(e.removeEventListener("focus",s._onCanvasFocus),e.removeEventListener("blur",s._onCanvasBlur),e.removeEventListener("pointerout",s._onCanvasPointerOut),e.removeEventListener("contextmenu",s._onCanvasContextMenu)),MS()&&(document.removeEventListener("fullscreenchange",s._onFullscreenChange),document.removeEventListener("mozfullscreenchange",s._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",s._onFullscreenChange),document.removeEventListener("msfullscreenchange",s._onFullscreenChange),document.removeEventListener("pointerlockchange",s._onPointerLockChange),document.removeEventListener("mspointerlockchange",s._onPointerLockChange),document.removeEventListener("mozpointerlockchange",s._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",s._onPointerLockChange))}function Bge(s){const e=document.createElement("span");e.textContent="Hg",e.style.font=s;const t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";const i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let r=0,n=0;try{n=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",r=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:r,height:n,descent:n-r}}function kge(s,e,t){return new Promise((r,n)=>{const a=new Image;a.onload=()=>{a.decode().then(()=>{s.createImageBitmap(a,t).then(o=>{r(o)})})},a.onerror=()=>{n(`Error loading image ${a.src}`)},a.src=e})}function Uge(s,e,t,i){const n=s.createCanvas(t,i).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");return n.drawImage(e,0,0),n.getImageData(0,0,t,i).data}function zge(s){const e=s.requestFullscreen||s.webkitRequestFullscreen;e&&e.call(s)}function Vge(){const s=document;document.exitFullscreen?document.exitFullscreen():s.webkitCancelFullScreen&&s.webkitCancelFullScreen()}function VJ(s){if(s.requestPointerLock){const e=s.requestPointerLock();e instanceof Promise?e.then(()=>{s.focus()}).catch(()=>{}):s.focus()}}function Gge(){document.exitPointerLock&&document.exitPointerLock()}class vt extends bi{static get NpmPackage(){return Ge.NpmPackage}static get Version(){return Ge.Version}static get Instances(){return Rt.Instances}static get LastCreatedEngine(){return Rt.LastCreatedEngine}static get LastCreatedScene(){return Rt.LastCreatedScene}static DefaultLoadingScreenFactory(e){return Ge.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!vt._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,r=!1){if(super(e,t,i,r),this.customAnimationFrameRequester=null,this._performanceMonitor=new Oge,this._drawCalls=new io,!!e&&(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext)){const n=e;this._sharedInit(n)}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),Nge(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return Uge(this,e,t,i)}_createImageBitmapFromSource(e,t){return kge(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&zge(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Vge()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,i,r){const n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),n}scissorClear(e,t,i,r,n){this.enableScissor(e,t,i,r),this.clear(n,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){const n=this._gl;n.enable(n.SCISSOR_TEST),n.scissor(e,t,i,r)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,i){return new Promise((r,n)=>{this._loadFile(e,a=>{r(a)},void 0,t,i,(a,o)=>{n(o)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Bge(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&VJ(this._renderingCanvas)}exitPointerlock(){Gge()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,n,a=null){n=n||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,r,n,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,r,n=null){const a=r.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");if(r.attachShader(a,t),r.attachShader(a,i),this.webGLVersion>1&&n){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(a,n),e.transformFeedback=o}return r.linkProgram(a),this.webGLVersion>1&&n&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(i=>{i._outputTexture===e&&(i._outputTexture=null)}),t.cameras.forEach(i=>{i._postProcesses.forEach(r=>{r&&r._outputTexture===e&&(r._outputTexture=null)})})})}_rescaleTexture(e,t,i,r,n){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const a=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&vt._RescalePostProcessFactory&&(this._rescalePostProcess=vt._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const o=()=>{this._rescalePostProcess.onApply=function(u){u._bindTexture("textureSampler",e)};let c=i;c||(c=this.scenes[this.scenes.length-1]),c.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),n&&n()},l=this._rescalePostProcess.getEffect();l?l.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce(c=>{c.executeWhenCompiled(o)})}}wrapWebGLTexture(e,t=!1,i=3,r=0,n=0){const a=new tT(e,this._gl),o=new zr(this,0,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){const n=this._gl,a=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),c=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);let u=n.TEXTURE_2D;e.isCube&&(u=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(u,r,l,o,a,t),this._bindTextureDirectly(c,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){fe.Error("WebGL 1 does not support texture comparison.");return}const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),t===0?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new rw(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const r=this._gl;return new Promise((n,a)=>{const o=()=>{const l=r.clientWaitSync(e,t,0);if(l==r.WAIT_FAILED){a();return}if(l==r.TIMEOUT_EXPIRED){setTimeout(o,i);return}n()};o()})}_readPixelsAsync(e,t,i,r,n,a,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,c=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,r,n,a,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);const u=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return u?(l.flush(),this._clientWaitAsync(u,0,10).then(()=>(l.deleteSync(u),l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(c),o))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),Fge(this,this._renderingCanvas),super.dispose()}}vt.ALPHA_DISABLE=0;vt.ALPHA_ADD=1;vt.ALPHA_COMBINE=2;vt.ALPHA_SUBTRACT=3;vt.ALPHA_MULTIPLY=4;vt.ALPHA_MAXIMIZED=5;vt.ALPHA_ONEONE=6;vt.ALPHA_PREMULTIPLIED=7;vt.ALPHA_PREMULTIPLIED_PORTERDUFF=8;vt.ALPHA_INTERPOLATE=9;vt.ALPHA_SCREENMODE=10;vt.DELAYLOADSTATE_NONE=0;vt.DELAYLOADSTATE_LOADED=1;vt.DELAYLOADSTATE_LOADING=2;vt.DELAYLOADSTATE_NOTLOADED=4;vt.NEVER=512;vt.ALWAYS=519;vt.LESS=513;vt.EQUAL=514;vt.LEQUAL=515;vt.GREATER=516;vt.GEQUAL=518;vt.NOTEQUAL=517;vt.KEEP=7680;vt.REPLACE=7681;vt.INCR=7682;vt.DECR=7683;vt.INVERT=5386;vt.INCR_WRAP=34055;vt.DECR_WRAP=34056;vt.TEXTURE_CLAMP_ADDRESSMODE=0;vt.TEXTURE_WRAP_ADDRESSMODE=1;vt.TEXTURE_MIRROR_ADDRESSMODE=2;vt.TEXTUREFORMAT_ALPHA=0;vt.TEXTUREFORMAT_LUMINANCE=1;vt.TEXTUREFORMAT_LUMINANCE_ALPHA=2;vt.TEXTUREFORMAT_RGB=4;vt.TEXTUREFORMAT_RGBA=5;vt.TEXTUREFORMAT_RED=6;vt.TEXTUREFORMAT_R=6;vt.TEXTUREFORMAT_RG=7;vt.TEXTUREFORMAT_RED_INTEGER=8;vt.TEXTUREFORMAT_R_INTEGER=8;vt.TEXTUREFORMAT_RG_INTEGER=9;vt.TEXTUREFORMAT_RGB_INTEGER=10;vt.TEXTUREFORMAT_RGBA_INTEGER=11;vt.TEXTURETYPE_UNSIGNED_BYTE=0;vt.TEXTURETYPE_UNSIGNED_INT=0;vt.TEXTURETYPE_FLOAT=1;vt.TEXTURETYPE_HALF_FLOAT=2;vt.TEXTURETYPE_BYTE=3;vt.TEXTURETYPE_SHORT=4;vt.TEXTURETYPE_UNSIGNED_SHORT=5;vt.TEXTURETYPE_INT=6;vt.TEXTURETYPE_UNSIGNED_INTEGER=7;vt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;vt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;vt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;vt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;vt.TEXTURETYPE_UNSIGNED_INT_24_8=12;vt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;vt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;vt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;vt.TEXTURE_NEAREST_SAMPLINGMODE=1;vt.TEXTURE_BILINEAR_SAMPLINGMODE=2;vt.TEXTURE_TRILINEAR_SAMPLINGMODE=3;vt.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;vt.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;vt.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;vt.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;vt.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;vt.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;vt.TEXTURE_NEAREST_LINEAR=7;vt.TEXTURE_NEAREST_NEAREST=1;vt.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;vt.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;vt.TEXTURE_LINEAR_LINEAR=2;vt.TEXTURE_LINEAR_NEAREST=12;vt.TEXTURE_EXPLICIT_MODE=0;vt.TEXTURE_SPHERICAL_MODE=1;vt.TEXTURE_PLANAR_MODE=2;vt.TEXTURE_CUBIC_MODE=3;vt.TEXTURE_PROJECTION_MODE=4;vt.TEXTURE_SKYBOX_MODE=5;vt.TEXTURE_INVCUBIC_MODE=6;vt.TEXTURE_EQUIRECTANGULAR_MODE=7;vt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;vt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;vt.SCALEMODE_FLOOR=1;vt.SCALEMODE_NEAREST=2;vt.SCALEMODE_CEILING=3;bi.prototype.createRenderTargetCubeTexture=function(s,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,s),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);const r=this._gl,n=new zr(this,5);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,fe.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let l=0;l<6;l++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),s,s,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,s,s),i.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,n.width=s,n.height=s,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n.format=i.format,this._internalTexturesCache.push(n),t.setTextures(n),t};bi.prototype.setDepthStencilTexture=function(s,e,t,i){s!==void 0&&(e&&(this._boundUniforms[s]=e),!t||!t.depthStencilTexture?this._setTexture(s,null,void 0,void 0,i):this._setTexture(s,t,!1,!0,i))};const Rne={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Pz{constructor(e,t=Rne){this._fullscreenViewport=new uc(0,0,1,1);const i=t.positions??Rne.positions,r=t.indices??Rne.indices;this.engine=e,this._vertexBuffers={[$.PositionKind]:new $(e,i,$.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(r);for(const n in this._vertexBuffers)this._vertexBuffers[n]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[$.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[$.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class J1{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new Ae;let t;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));const r=e.defines?e.defines.join(` `):"";this._drawWrapper=new Ro(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new zi(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const cBe="passPixelShader",uBe=`varying vec2 vUV;uniform sampler2D textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);}`;de.ShadersStore[cBe]=uBe;const uZ={name:cBe,shader:uBe},D2t=Object.freeze(Object.defineProperty({__proto__:null,passPixelShader:uZ},Symbol.toStringTag,{value:"Module"}));let Dy;function L2t(){if(!Dy){let s,e=null;const t={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{s=new OffscreenCanvas(100,100),e=new bi(s,!1,t)}catch{s=document.createElement("canvas"),e=new bi(s,!1,t)}Rt.Instances.pop(),Rt.OnEnginesDisposedObservable.add(n=>{e&&n!==e&&!e.isDisposed&&Rt.Instances.length===0&&hBe()}),e.getCaps().parallelShaderCompile=void 0;const i=new Pz(e),r=new J1({engine:e,name:uZ.name,fragmentShader:uZ.shader,samplerNames:["textureSampler"]});Dy={canvas:s,engine:e,renderer:i,wrapper:r}}return Dy}async function Wge(s,e,t,i,r="image/png",n,a){const o=await t.readPixels(0,0,s,e),l=new Uint8Array(o.buffer);e6(s,e,l,i,r,n,!0,void 0,a)}function Kge(s,e,t,i="image/png",r,n=!1,a=!1,o){return new Promise(l=>{e6(s,e,t,c=>l(c),i,r,n,a,o)})}function e6(s,e,t,i,r="image/png",n,a=!1,o=!1,l){const c=L2t();if(c.engine.setSize(s,e,!0),t instanceof Float32Array){const h=new Uint8Array(t.length);let d=t.length;for(;d--;){const f=t[d];h[d]=Math.round(At.Clamp(f)*255)}t=h}const u=c.engine.createRawTexture(t,s,e,5,!1,!a,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),o?Me.ToBlob(c.canvas,h=>{const d=new FileReader;d.onload=f=>{const p=f.target.result;i&&i(p)},d.readAsArrayBuffer(h)},r,l):Me.EncodeScreenshotCanvasData(c.canvas,i,r,n,l),u.dispose()}function hBe(){Dy&&(Dy.wrapper.dispose(),Dy.renderer.dispose(),Dy.engine.dispose()),Dy=null}const O2t={DumpData:e6,DumpDataAsync:Kge,DumpFramebuffer:Wge,Dispose:hBe},N2t=()=>{Me.DumpData=e6,Me.DumpDataAsync=Kge,Me.DumpFramebuffer=Wge};N2t();zi.prototype.setDepthStencilTexture=function(s,e){this._engine.setDepthStencilTexture(this._samplers[s],this._uniforms[s],e,s)};class Rs extends xe{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=TFe(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let r=0;r{var T;const C=this._renderList?this._renderList.length:0;(b===0&&C>0||C===0)&&((T=this.getScene())==null||T.meshes.forEach(w=>{w._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new Ae,this.onAfterUnbindObservable=new Ae,this.onBeforeRenderObservable=new Ae,this.onAfterRenderObservable=new Ae,this.onClearObservable=new Ae,this.onResizeObservable=new Ae,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=D.Zero(),i=this.getScene(),!i)return;const x=this.getScene().getEngine();this._gammaSpace=v,this._coordinatesMode=xe.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=n,this._renderingManager=new Wl(i),this._renderingManager._useSceneAutoClearSetup=!0,!h&&(this._renderTargetOptions={generateMipMaps:r,type:a,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:u,samples:p,creationFlags:m,noColorAttachment:g,useSRGBBuffer:_,colorAttachment:y,label:this.name},this.samplingMode===xe.NEAREST_SAMPLINGMODE&&(this.wrapU=xe.CLAMP_ADDRESSMODE,this.wrapV=xe.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=xe.INVCUBIC_MODE,this._textureMatrix=he.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,p!==void 0&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,n=14,a){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,r,n,a)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;const t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var r;const t=this.isCube;(r=this._renderTarget)==null||r.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const r=this.getScene();if(!r)return i;const n=r.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!r||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,n=null){var c,u,h;const a=this.getScene();if(!a)return;const o=a.getEngine();if((c=o._debugPushGroup)==null||c.call(o,`render to face #${e} layer #${r}`,1),this._prepareFrame(a,e,r,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&o.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||a.clearColor,!0,!0,!0);else{let d=null;const f=this.renderList?this.renderList:a.getActiveMeshes().data,p=this.renderList?this.renderList.length:a.getActiveMeshes().length;this.getCustomRenderList&&(d=this.getCustomRenderList(this.is2DArray||this.is3D?r:e,f,p)),d?this._prepareRenderingManager(d,d.length,n,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(f,p,n,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),d=f);for(const g of a._beforeRenderTargetClearStage)g.action(this,e,r);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||a.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||a.updateTransformMatrix(!0);for(const g of a._beforeRenderTargetDrawStage)g.action(this,e,r);this._renderingManager.render(this.customRenderFunction,d,this.renderParticles,this.renderSprites);for(const g of a._afterRenderTargetDrawStage)g.action(this,e,r);const m=((u=this._texture)==null?void 0:u.generateMipMaps)??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&a.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const g of a._afterRenderTargetPostProcessStage)g.action(this,e,r);this._texture&&(this._texture.generateMipMaps=m),this._doNotChangeAspectRatio||a.updateTransformMatrix(!0),i&&Wge(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&e===5&&o.generateMipMapsForCubemap(this._texture,!0),(h=o._debugPopGroup)==null||h.call(o,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new Rs(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const r of e.cameras)t=r.customRenderTargets.indexOf(this),t>=0&&r.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Rs.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Rs.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Rs.REFRESHRATE_RENDER_ONCE=0;Rs.REFRESHRATE_RENDER_ONEVERYFRAME=1;Rs.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;xe._CreateRenderTargetTexture=(s,e,t,i,r)=>new Rs(s,e,t,i);class Gue extends Rs{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}vt.prototype.createMultiviewRenderTargetTexture=function(s,e,t,i){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:s,height:e});n._framebuffer=r.createFramebuffer();const a=new zr(this,0,!0);return a.width=s,a.height=e,a.isMultiview=!0,t||(t=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,t),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,s,e,2)),n._colorTextureArray=t,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,s,e,2)),n._depthStencilTextureArray=i,a.isReady=!0,n.setTextures(a),n._depthStencilTexture=a,n};vt.prototype.bindMultiviewFramebuffer=function(s){const e=s,t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"};vt.prototype.bindSpaceWarpFramebuffer=function(s){const e=s,t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw new Error("Invalid Space Warp framebuffer")};Nt.prototype._useMultiviewToSingleView=!1;Nt.prototype._multiviewTexture=null;Nt.prototype._resizeOrCreateMultiviewTexture=function(s,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=s||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new Gue(this.getScene(),{width:s,height:e})):this._multiviewTexture=new Gue(this.getScene(),{width:s,height:e})};function dBe(s,e){const t=new zt(s,void 0,!0,e);return t.addUniform("viewProjection",16),t.addUniform("viewProjectionR",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}const F2t=gt.prototype.createSceneUniformBuffer;gt.prototype._transformMatrixR=he.Zero();gt.prototype._multiviewSceneUbo=null;gt.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=dBe(this.getEngine(),"scene_multiview")};gt.prototype.createSceneUniformBuffer=function(s){return this._multiviewSceneUbo?dBe(this.getEngine(),s):F2t.bind(this)(s)};gt.prototype._updateMultiviewUbo=function(s,e){s&&e&&s.multiplyToRef(e,this._transformMatrixR),s&&e&&(s.multiplyToRef(e,se.Matrix[0]),Od.GetRightPlaneToRef(se.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))};gt.prototype._renderMultiviewToSingleView=function(s){s._resizeOrCreateMultiviewTexture(s._rigPostProcess&&s._rigPostProcess&&s._rigPostProcess.width>0?s._rigPostProcess.width:this.getEngine().getRenderWidth(!0),s._rigPostProcess&&s._rigPostProcess&&s._rigPostProcess.height>0?s._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),s.outputRenderTarget=s._multiviewTexture,this._renderForCamera(s),s.outputRenderTarget=null;for(let e=0;e{}),this.onApplyObservable.add(n=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?n.setInt("imageIndex",0):n.setInt("imageIndex",1),n.setTexture("multiviewSampler",r._multiviewTexture)})}}function GJ(s,e){const t=e.vrCameraMetrics||nT.GetDefault();s._rigCameras[0]._cameraRigParams.vrMetrics=t,s._rigCameras[0].viewport=new uc(0,0,.5,1),s._rigCameras[0]._cameraRigParams.vrWorkMatrix=new he,s._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,s._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,s._rigCameras[0].getProjectionMatrix=s._rigCameras[0]._getVRProjectionMatrix,s._rigCameras[1]._cameraRigParams.vrMetrics=t,s._rigCameras[1].viewport=new uc(.5,0,.5,1),s._rigCameras[1]._cameraRigParams.vrWorkMatrix=new he,s._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,s._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,s._rigCameras[1].getProjectionMatrix=s._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(s.getScene().getEngine().getCaps().multiview?(s._useMultiviewToSingleView=!0,s._rigPostProcess=new fBe("VRMultiviewToSingleview",s,t.postProcessScaleFactor)):(fe.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(s._rigCameras[0]._rigPostProcess=new Vue("VR_Distort_Compensation_Left",s._rigCameras[0],!1,t),s._rigCameras[1]._rigPostProcess=new Vue("VR_Distort_Compensation_Right",s._rigCameras[1],!0,t))}ns.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(s,e)=>()=>new pBe(s,0,0,1,D.Zero(),e));class pBe extends Kr{constructor(e,t,i,r,n,a,o=!0,l=nT.GetDefault()){super(e,t,i,r,n,a),this._setRigMode=c=>GJ(this,c),l.compensateDistortion=o,this.setCameraRigMode(Nt.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}ns.AddNodeConstructor("VRDeviceOrientationFreeCamera",(s,e)=>()=>new WJ(s,D.Zero(),e));class WJ extends UJ{constructor(e,t,i,r=!0,n=nT.GetDefault()){super(e,t,i),this._setRigMode=a=>GJ(this,a),n.compensateDistortion=r,this.setCameraRigMode(Nt.RIG_MODE_VR,{vrCameraMetrics:n})}getClassName(){return"VRDeviceOrientationFreeCamera"}}ns.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(s,e)=>()=>new mBe(s,D.Zero(),e));class mBe extends WJ{constructor(e,t,i,r=!0,n=nT.GetDefault()){super(e,t,i,r,n),this._setRigMode=a=>GJ(this,a),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class hZ{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,n){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&t.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const a=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==a.frameId&&(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}class _s{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e))}_setDefaultValue(e){var r,n,a,o;const t=((n=(r=this._externalProperties)==null?void 0:r[e])==null?void 0:n.type)??typeof this[e],i=(o=(a=this._externalProperties)==null?void 0:a[e])==null?void 0:o.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1;break}}toString(){let e="";for(let t=0;tthis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let r=0;r0&&(n.computeBonesUsingShaders=!1);continue}if(!(!n.computeBonesUsingShaders||n.numBoneInfluencers===0)){if(n.material.getEffect()===t)n.computeBonesUsingShaders=!1;else if(n.subMeshes){for(const a of n.subMeshes)if(a.effect===t){n.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let r=0;rthis._handlePluginEvent(r,n),this._plugins.push(e),this._plugins.sort((r,n)=>r.priority-n.priority),this._codeInjectionPoints={};const i={};i[cv._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const r of this._plugins)r.collectDefines(i),this._collectPointNames("vertex",r.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",r.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&i.uniforms.push(...this._uniformList),this._samplerList.length>0&&i.samplers.push(...this._samplerList),this._uboList.length>0&&i.uniformBuffersNames.push(...this._uboList),i.customCode=this._injectCustomCode(i,i.customCode);break}case 8:{const i=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];const r=this._material.shaderLanguage===1;for(const n of this._plugins){const a=n.getUniforms(this._material.shaderLanguage);if(a){if(a.ubo)for(const o of a.ubo){if(o.size&&o.type){const l=o.arraySize??0;if(i.ubo.addUniform(o.name,o.size,l),r){let c;switch(o.type){case"mat4":c="mat4x4f";break;case"float":c="f32";break;default:c=`${o.type}f`;break}this._uboDeclaration+=`uniform ${o.name}: ${c}${l>0?`[${l}]`:""}; `}else this._uboDeclaration+=`${o.type} ${o.name}${l>0?`[${l}]`:""}; `}this._uniformList.push(o.name)}a.vertex&&(this._vertexDeclaration+=a.vertex+` `),a.fragment&&(this._fragmentDeclaration+=a.fragment+` `)}n.getSamplers(this._samplerList),n.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var o,l;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const n=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!n)return r;let a=null;for(let c in n){let u="";for(const h of this._activePlugins){let d=(l=h.getCustomCode(i,this._material.shaderLanguage))==null?void 0:l[c];d&&(h.resolveIncludes&&(a===null&&(a={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:de.GetShadersRepository(0),includesShadersStore:de.GetIncludesShadersStore(0),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}),a.isFragment=i==="fragment",Ok(d,a,f=>d=f)),u+=d+` `)}if(u.length>0)if(c.charAt(0)==="!"){c=c.substring(1);let h="g";if(c.charAt(0)==="!")h="",c=c.substring(1);else{const m=B2t.exec(c);m&&m.length>=2&&(h=m[1],c=c.substring(h.length+1))}h.indexOf("g")<0&&(h+="g");const d=r,f=new RegExp(c,h);let p=f.exec(d);for(;p!==null;){let m=u;for(let g=0;g{Hge()});const Fy=[];let Wue=!1,Kue=null;function k2t(s,e){Wue||(Kue=Ye.OnEventObservable.add(i=>{for(const[,r]of Fy)r(i)},1),Wue=!0);const t=Fy.filter(([i,r])=>i===s);t.length>0?t[0][1]=e:Fy.push([s,e])}function U2t(s){for(let e=0;e{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,n&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;const i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){qe.Clone(()=>e,this)}serialize(){return qe.Serialize(this)}parse(e,t,i){qe.Parse(()=>this,e,t,i)}}F([X()],fu.prototype,"name",void 0);F([X()],fu.prototype,"priority",void 0);F([X()],fu.prototype,"resolveIncludes",void 0);F([X()],fu.prototype,"registerForExtraEvents",void 0);ve("BABYLON.MaterialPluginBase",fu);class gBe extends _s{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class C_ extends fu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new gBe,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ye.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&Je.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&Je.DetailTextureEnabled&&this._isEnabled?(rn(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&Je.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),sn(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Je.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}F([ii("detailTexture"),Fe("_markAllSubMeshesAsTexturesDirty")],C_.prototype,"texture",void 0);F([X()],C_.prototype,"diffuseBlendLevel",void 0);F([X()],C_.prototype,"roughnessBlendLevel",void 0);F([X()],C_.prototype,"bumpLevel",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],C_.prototype,"normalBlendMethod",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],C_.prototype,"isEnabled",void 0);const Ine={effect:null,subMesh:null};class _Be extends _s{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class et extends aa{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Re(0,0,0),this.diffuseColor=new Re(1,1,1),this.specularColor=new Re(1,1,1),this.emissiveColor=new Re(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._renderTargets=new no(16),this._worldViewProjectionMatrix=he.Zero(),this._globalAmbientColor=new Re(0,0,0),this._cacheHasRenderTargetTextures=!1;const r=this.getScene().getEngine();r.isWebGPU&&!i&&!et.ForceGLSL&&(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new zt(r,void 0,void 0,this.name,!0),this._shaderLanguage=1),this.detailMap=new C_(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new hZ,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),et.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),et.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return et.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||et.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._forceAlphaTest?!0:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ye.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ye.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new _Be(this._eventInfo.defineNames));const n=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();a._needNormals=du(n,e,a,!0,this._maxSimultaneousLights,this._disableLighting),qw(n,a);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(mz(n,a,this.canRenderToMRT&&!l),OJ(n,a,l),a._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a._needUVs=!1;for(let u=1;u<=6;++u)a["MAINUV"+u]=!1;if(n.texturesEnabled){if(a.DIFFUSEDIRECTUV=0,a.BUMPDIRECTUV=0,a.AMBIENTDIRECTUV=0,a.OPACITYDIRECTUV=0,a.EMISSIVEDIRECTUV=0,a.SPECULARDIRECTUV=0,a.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&et.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())rn(this._diffuseTexture,a,"DIFFUSE");else return!1;else a.DIFFUSE=!1;if(this._ambientTexture&&et.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())rn(this._ambientTexture,a,"AMBIENT");else return!1;else a.AMBIENT=!1;if(this._opacityTexture&&et.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())rn(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else a.OPACITY=!1;if(this._reflectionTexture&&et.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(a._needNormals=!0,a.REFLECTION=!0,a.ROUGHNESS=this._roughness>0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===xe.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,a.REFLECTIONMAP_OPPOSITEZ=a.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,a.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case xe.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case xe.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case xe.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case xe.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case xe.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case xe.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case xe.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case xe.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case xe.CUBIC_MODE:case xe.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC");break}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else a.REFLECTION=!1,a.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&et.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())rn(this._emissiveTexture,a,"EMISSIVE");else return!1;else a.EMISSIVE=!1;if(this._lightmapTexture&&et.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())rn(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else a.LIGHTMAP=!1;if(this._specularTexture&&et.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())rn(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else a.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&et.BumpTextureEnabled){if(this._bumpTexture.isReady())rn(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=n.useRightHandedSystem,a.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1,a.PARALLAX=!1,a.PARALLAX_RHS=!1,a.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&et.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube,a.RGBDREFRACTION=this._refractionTexture.isRGBD,a.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,a.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=a,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}a._areFresnelDirty&&(et.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),Kc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,a,this._applyDecalMapAfterDetailMap),Hc(n,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=a,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Na(e,a,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let c=!1;if(a.isDirty){const u=a._areLightsDisposed;a.markAsProcessed();const h=new oa;a.REFLECTION&&h.addFallback(0,"REFLECTION"),a.SPECULAR&&h.addFallback(0,"SPECULAR"),a.BUMP&&h.addFallback(0,"BUMP"),a.PARALLAX&&h.addFallback(1,"PARALLAX"),a.PARALLAX_RHS&&h.addFallback(1,"PARALLAX_RHS"),a.PARALLAXOCCLUSION&&h.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&h.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&h.addFallback(1,"FOG"),a.POINTSIZE&&h.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&h.addFallback(0,"LOGARITHMICDEPTH"),Zo(a,h,this._maxSimultaneousLights),a.SPECULARTERM&&h.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&h.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&h.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&h.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&h.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&h.addFallback(4,"FRESNEL"),a.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");const d=[$.PositionKind];a.NORMAL&&d.push($.NormalKind),a.TANGENT&&d.push($.TangentKind);for(let b=1;b<=6;++b)a["UV"+b]&&d.push(`uv${b===1?"":b}`);a.VERTEXCOLOR&&d.push($.ColorKind),Vu(d,e,a,h),Ya(d,a),dz(d,e,a),Zw(d,e,a);let f="default";const p=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],m=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=0,this._eventInfo.defines=a,this._eventInfo.uniforms=p,this._eventInfo.attributes=d,this._eventInfo.samplers=m,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),hZ.AddUniforms(p),lr&&(lr.PrepareUniforms(p,a),lr.PrepareSamplers(m,a)),po({uniformsNames:p,uniformBuffersNames:g,samplers:m,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),fo(p);const y={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,g,m,a,d,y));const v=a.toString(),x=t.effect;let A=n.getEngine().createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:g,samplers:m,defines:v,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:y.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:a.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>oMt),void 0),Ue(()=>Promise.resolve().then(()=>sMt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>tMt),void 0),Ue(()=>Promise.resolve().then(()=>qTt),void 0)]),this._shadersLoaded=!0}},o);if(this._eventInfo.customCode=void 0,A)if(this._onEffectCreatedObservable&&(Ine.effect=A,Ine.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Ine)),this.allowShaderHotSwapping&&x&&!A.isReady()){if(A=x,a.markAsUnprocessed(),c=this.isFrozen,u)return a._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(A,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=n.getRenderId(),r._wasPreviouslyReady=!c,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var c;const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(r,a,i,t.visibility);ql(t,a);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||i._drawWrapper._forceRebindOnNextCall){if(et.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new Re(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&et.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),sn(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&et.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),sn(this._ambientTexture,l,"ambient")),this._opacityTexture&&et.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),sn(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&et.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const u=this._reflectionTexture;l.updateVector3("vReflectionPosition",u.boundingBoxPosition),l.updateVector3("vReflectionSize",u.boundingBoxSize)}if(this._emissiveTexture&&et.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),sn(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&et.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),sn(this._lightmapTexture,l,"lightmap")),this._specularTexture&&et.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),sn(this._specularTexture,l,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&et.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),sn(this._bumpTexture,l,"bump"),r._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&et.RefractionTextureEnabled){let u=1;if(this._refractionTexture.isCube||(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(u=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,u,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const h=this._refractionTexture;l.updateVector3("vRefractionPosition",h.boundingBoxPosition),l.updateVector3("vRefractionSize",h.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",et.EmissiveTextureEnabled?this.emissiveColor:Re.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&et.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&et.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&et.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&et.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&et.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&et.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&et.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&et.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&et.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Xa(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&hu(r,t,a,n,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==gt.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),ml(r,t,a),n.NUM_MORPH_INFLUENCERS&&I0(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((c=t.bakedVertexAnimationManager)==null||c.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&uo(n,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),l.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,r,n,a,o,l,c,u,h;t&&((i=this._diffuseTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(n=this._opacityTexture)==null||n.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(c=this._bumpTexture)==null||c.dispose(),(u=this._lightmapTexture)==null||u.dispose(),(h=this._refractionTexture)==null||h.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const r=qe.Clone(()=>new et(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){const r=qe.Parse(()=>new et(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ye._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return Je.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Je.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Je.DetailTextureEnabled}static set DetailTextureEnabled(e){Je.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Je.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Je.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Je.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Je.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Je.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Je.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Je.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Je.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Je.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Je.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Je.BumpTextureEnabled}static set BumpTextureEnabled(e){Je.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Je.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Je.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Je.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Je.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Je.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Je.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Je.FresnelEnabled}static set FresnelEnabled(e){Je.FresnelEnabled=e}}et.ForceGLSL=!1;F([ii("diffuseTexture")],et.prototype,"_diffuseTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],et.prototype,"diffuseTexture",void 0);F([ii("ambientTexture")],et.prototype,"_ambientTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"ambientTexture",void 0);F([ii("opacityTexture")],et.prototype,"_opacityTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],et.prototype,"opacityTexture",void 0);F([ii("reflectionTexture")],et.prototype,"_reflectionTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"reflectionTexture",void 0);F([ii("emissiveTexture")],et.prototype,"_emissiveTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"emissiveTexture",void 0);F([ii("specularTexture")],et.prototype,"_specularTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"specularTexture",void 0);F([ii("bumpTexture")],et.prototype,"_bumpTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"bumpTexture",void 0);F([ii("lightmapTexture")],et.prototype,"_lightmapTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"lightmapTexture",void 0);F([ii("refractionTexture")],et.prototype,"_refractionTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"refractionTexture",void 0);F([br("ambient")],et.prototype,"ambientColor",void 0);F([br("diffuse")],et.prototype,"diffuseColor",void 0);F([br("specular")],et.prototype,"specularColor",void 0);F([br("emissive")],et.prototype,"emissiveColor",void 0);F([X()],et.prototype,"specularPower",void 0);F([X("useAlphaFromDiffuseTexture")],et.prototype,"_useAlphaFromDiffuseTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],et.prototype,"useAlphaFromDiffuseTexture",void 0);F([X("useEmissiveAsIllumination")],et.prototype,"_useEmissiveAsIllumination",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useEmissiveAsIllumination",void 0);F([X("linkEmissiveWithDiffuse")],et.prototype,"_linkEmissiveWithDiffuse",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"linkEmissiveWithDiffuse",void 0);F([X("useSpecularOverAlpha")],et.prototype,"_useSpecularOverAlpha",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useSpecularOverAlpha",void 0);F([X("useReflectionOverAlpha")],et.prototype,"_useReflectionOverAlpha",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useReflectionOverAlpha",void 0);F([X("disableLighting")],et.prototype,"_disableLighting",void 0);F([Fe("_markAllSubMeshesAsLightsDirty")],et.prototype,"disableLighting",void 0);F([X("useObjectSpaceNormalMap")],et.prototype,"_useObjectSpaceNormalMap",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useObjectSpaceNormalMap",void 0);F([X("useParallax")],et.prototype,"_useParallax",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useParallax",void 0);F([X("useParallaxOcclusion")],et.prototype,"_useParallaxOcclusion",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useParallaxOcclusion",void 0);F([X()],et.prototype,"parallaxScaleBias",void 0);F([X("roughness")],et.prototype,"_roughness",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"roughness",void 0);F([X()],et.prototype,"indexOfRefraction",void 0);F([X()],et.prototype,"invertRefractionY",void 0);F([X()],et.prototype,"alphaCutOff",void 0);F([X("useLightmapAsShadowmap")],et.prototype,"_useLightmapAsShadowmap",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useLightmapAsShadowmap",void 0);F([Kw("diffuseFresnelParameters")],et.prototype,"_diffuseFresnelParameters",void 0);F([Fe("_markAllSubMeshesAsFresnelDirty")],et.prototype,"diffuseFresnelParameters",void 0);F([Kw("opacityFresnelParameters")],et.prototype,"_opacityFresnelParameters",void 0);F([Fe("_markAllSubMeshesAsFresnelAndMiscDirty")],et.prototype,"opacityFresnelParameters",void 0);F([Kw("reflectionFresnelParameters")],et.prototype,"_reflectionFresnelParameters",void 0);F([Fe("_markAllSubMeshesAsFresnelDirty")],et.prototype,"reflectionFresnelParameters",void 0);F([Kw("refractionFresnelParameters")],et.prototype,"_refractionFresnelParameters",void 0);F([Fe("_markAllSubMeshesAsFresnelDirty")],et.prototype,"refractionFresnelParameters",void 0);F([Kw("emissiveFresnelParameters")],et.prototype,"_emissiveFresnelParameters",void 0);F([Fe("_markAllSubMeshesAsFresnelDirty")],et.prototype,"emissiveFresnelParameters",void 0);F([X("useReflectionFresnelFromSpecular")],et.prototype,"_useReflectionFresnelFromSpecular",void 0);F([Fe("_markAllSubMeshesAsFresnelDirty")],et.prototype,"useReflectionFresnelFromSpecular",void 0);F([X("useGlossinessFromSpecularMapAlpha")],et.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"useGlossinessFromSpecularMapAlpha",void 0);F([X("maxSimultaneousLights")],et.prototype,"_maxSimultaneousLights",void 0);F([Fe("_markAllSubMeshesAsLightsDirty")],et.prototype,"maxSimultaneousLights",void 0);F([X("invertNormalMapX")],et.prototype,"_invertNormalMapX",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"invertNormalMapX",void 0);F([X("invertNormalMapY")],et.prototype,"_invertNormalMapY",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"invertNormalMapY",void 0);F([X("twoSidedLighting")],et.prototype,"_twoSidedLighting",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],et.prototype,"twoSidedLighting",void 0);F([X("applyDecalMapAfterDetailMap")],et.prototype,"_applyDecalMapAfterDetailMap",void 0);F([Fe("_markAllSubMeshesAsMiscDirty")],et.prototype,"applyDecalMapAfterDetailMap",void 0);ve("BABYLON.StandardMaterial",et);gt.DefaultMaterialFactory=s=>new et("default material",s);bi.prototype.createDynamicTexture=function(s,e,t,i){const r=new zr(this,4);return r.baseWidth=s,r.baseHeight=e,t&&(s=this.needPOTTextures?ad(s,this._caps.maxTextureSize):s,e=this.needPOTTextures?ad(e,this._caps.maxTextureSize):e),r.width=s,r.height=e,r.isReady=!1,r.generateMipMaps=t,r.samplingMode=i,this.updateTextureSamplingMode(i,r),this._internalTexturesCache.push(r),r};bi.prototype.updateDynamicTexture=function(s,e,t,i=!1,r,n=!1,a=!1){if(!s)return;const o=this._gl,l=o.TEXTURE_2D,c=this._bindTextureDirectly(l,s,!0,n);this._unpackFlipY(t===void 0?s.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const u=this._getWebGLTextureType(s.type),h=this._getInternalFormat(r||s.format),d=this._getRGBABufferInternalSizedFormat(s.type,h);o.texImage2D(l,0,d,h,u,e),s.generateMipMaps&&o.generateMipmap(l),c||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(s.format=r),s._dynamicTextureSource=e,s._premulAlpha=i,s.invertY=t||!1,s.isReady=!0};class Qf extends xe{constructor(e,t,i=null,r=!1,n=3,a=5,o){super(null,i,!r,o,n,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=xe.CLAMP_ADDRESSMODE,this.wrapV=xe.CLAMP_ADDRESSMODE,this._generateMipMaps=r;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(t.width,t.height,r,n)):(this._canvas=l.createCanvas(1,1),this._ownCanvas=!0,t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,r,n):this._texture=l.createDynamicTexture(t,t,r,n));const c=this.getSize();this._canvas.width!==c.width&&(this._canvas.width=c.width),this._canvas.height!==c.height&&(this._canvas.height=c.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,n,a,o,l=!0){const c=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,c.width,c.height)),this._context.font=r,t==null){const u=this._context.measureText(e);t=(c.width-u.width)/2}if(i==null){const u=parseInt(r.replace(/\D/g,""));i=c.height/2+u/3.65}this._context.fillStyle=n||"",this._context.fillText(e,t,i),l&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Qf(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&fe.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Qf._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}class jge{get isFixedFoveationSupported(){return this.layerType=="XRWebGLLayer"&&typeof this.layer.fixedFoveation=="number"}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,r,n){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this._createRenderTargetTextureProvider=n,this._rttWrapper=null}}class KJ{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new zr(this._engine,0,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new tT(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,n,a){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},l=a?new Gue(this._scene,o):new Rs("XR renderTargetTexture",o,this._scene),c=l.renderTarget;if(c._samples=l.samples,(i||!r)&&(c._framebuffer=i),r)if(a)c._colorTextureArray=r;else{const u=this._createInternalTexture(o,r);c.setTexture(u,0),l._texture=u}return n&&(a?c._depthStencilTextureArray=n:c._depthStencilTexture=this._createInternalTexture(o,n)),l.disableRescaling(),this._renderTargetTextures.push(l),l}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}}class Xge extends jge{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new z2t(t.scene,this)),this.layer=e}}class z2t extends KJ{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const r=this._framebufferDimensions.framebufferWidth,n=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/n,e.width=i.width/r,e.height=i.height/n,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return(!this._rtt||t!==this._framebufferDimensions.framebufferWidth||i!==this._framebufferDimensions.framebufferHeight||r!==this._framebuffer)&&(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class wz{static GetDefaults(e){const t=new wz;return t.canvasOptions={antialias:!0,depth:!0,stencil:e?e.isStencilEnable:!0,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class vBe{constructor(e,t=wz.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new Ae,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const i=document.createElement("canvas");i.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(i)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()}),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise((e,t)=>{try{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{e()},()=>{Me.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly."),e()}):e()}catch(i){t(i)}})}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Xge(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then(()=>{},()=>{}).then(()=>t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){!this._canvas||!this._engine||(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class yBe extends jge{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new xBe(t,this)),this.layer=e}}class xBe extends KJ{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class ABe{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class Dz{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new Ae,this.onXRReferenceSpaceChanged=new Ae,this.onXRSessionEnded=new Ae,this.onXRSessionInit=new Ae,this.onXRReferenceSpaceInitialized=new Ae,this.onXRReady=new Ae,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new Ae(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),(e=this._engine)==null||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{fe.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){var i;return((i=this._baseLayerRTTProvider)==null?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return((t=this._baseLayerRTTProvider)==null?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return((t=this._baseLayerRTTProvider)==null?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new ABe(this):(e=e||wz.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new vBe(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(i=>(this.session=i,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(i),this.session.addEventListener("end",()=>{var r;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&((r=this._baseLayerRTTProvider)==null||r.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return Dz.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;!this.inXRSession||!this._engine||(this._engine.customAnimationFrameRequester={requestAnimationFrame:t=>this.session.requestAnimationFrame(t),renderFunction:(t,i)=>{var r;if(!(!this.inXRSession||!this._engine)&&(this.currentFrame=i,this.currentTimestamp=t,i)){this.inXRFrameLoop=!0;const n=((r=this._baseLayerRTTProvider)==null?void 0:r.getFramebufferDimensions())||null;this._engine.framebufferDimensionsObject!==n&&(this._engine.framebufferDimensionsObject=n),this.onXRFrameObservable.notifyObservers(i),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=((e=this._baseLayerRTTProvider)==null?void 0:e.getFramebufferDimensions())||null,this.onXRFrameObservable.addOnce(()=>{this.onXRReady.notifyObservers(this)}),typeof window<"u"&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(t=>t,t=>(fe.Error("XR.requestReferenceSpace failed for the following reason: "),fe.Error(t),fe.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(i=>{const r=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(r)},i=>{throw fe.Error(i),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(t=>this.session.requestReferenceSpace("viewer").then(i=>(this.viewerReferenceSpace=i,t))).then(t=>(this.referenceSpace=this.baseReferenceSpace=t,this.onXRReferenceSpaceInitialized.notifyObservers(t),this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&((t=this._baseLayerRTTProvider)==null||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=((i=this._baseLayerWrapper)==null?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new yBe(e.baseLayer):new Xge(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(i=>{const r=typeof i>"u"?!0:i;return Promise.resolve(r)}).catch(i=>(fe.Warn(i),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){var e;return(e=this.session)==null?void 0:e.frameRate}get supportedFrameRates(){var e;return(e=this.session)==null?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return((e=this._baseLayerWrapper)==null?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return((e=this._baseLayerWrapper)==null?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){var e;return((e=this.session)==null?void 0:e.enabledFeatures)??null}}Ee._GroundMeshParser=(s,e)=>tD.Parse(s,e);class tD extends Ee{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),r=se.Matrix[5];i.invertToRef(r);const n=se.Vector3[8];if(D.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t),o=-(a.x*e+a.z*t+a.w)/a.y;return D.TransformCoordinatesFromFloatsToRef(0,o,0,i,n),n.y}getNormalAtCoordinates(e,t){const i=new D(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const r=this.getWorldMatrix(),n=se.Matrix[5];r.invertToRef(n);const a=se.Vector3[8];if(D.TransformCoordinatesFromFloatsToRef(e,0,t,n,a),e=a.x,t=a.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return D.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[r*this._subdivisionsX+i];let a;return ts.maxHeight){c=!0;const h=s.maxHeight;s.maxHeight=s.minHeight,s.minHeight=h}for(n=0;n<=s.subdivisions;n++)for(a=0;a<=s.subdivisions;a++){const h=new D(a*s.width/s.subdivisions-s.width/2,0,(s.subdivisions-n)*s.height/s.subdivisions-s.height/2),d=(h.x+s.width/2)/s.width*(s.bufferWidth-1)|0,f=(1-(h.z+s.height/2)/s.height)*(s.bufferHeight-1)|0,p=(d+f*s.bufferWidth)*4;let m=s.buffer[p]/255,g=s.buffer[p+1]/255,_=s.buffer[p+2]/255;const y=s.buffer[p+3]/255;c&&(m=1-m,g=1-g,_=1-_);const v=m*o.r+g*o.g+_*o.b;y>=l?h.y=s.minHeight+(s.maxHeight-s.minHeight)*v:h.y=s.minHeight-ci,s.heightBuffer&&(s.heightBuffer[n*(s.subdivisions+1)+a]=h.y),t.push(h.x,h.y,h.z),i.push(0,0,0),r.push(a/s.subdivisions,1-n/s.subdivisions)}for(n=0;n=s.minHeight,g=t[d*3+1]>=s.minHeight,_=t[f*3+1]>=s.minHeight;m&&g&&_&&(e.push(h),e.push(d),e.push(f)),t[p*3+1]>=s.minHeight&&m&&_&&(e.push(p),e.push(h),e.push(f))}at.ComputeNormals(t,e,i);const u=new at;return u.indices=e,u.positions=t,u.normals=i,u.uvs=r,u}function aT(s,e={},t){const i=new tD(s,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,P1(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function HJ(s,e,t=null){const i=new Ee(s,t);return Yge(e).applyToMesh(i,e.updatable),i}function jJ(s,e,t={},i=null){const r=t.width||10,n=t.height||10,a=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,c=t.colorFilter||new Re(.3,.59,.11),u=t.alphaFilter||0,h=t.updatable,d=t.onReady;i=i||Rt.LastCreatedScene;const f=new tD(s,i);f._subdivisionsX=a,f._subdivisionsY=a,f._width=r,f._height=n,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);let p;t.passHeightBufferInCallback&&(p=new Float32Array((a+1)*(a+1)));const m=(g,_,y)=>{Qge({width:r,height:n,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:c,buffer:g,bufferWidth:_,bufferHeight:y,alphaFilter:u,heightBuffer:p}).applyToMesh(f,h),d&&d(f,p),f._setReady(!0)};if(typeof e=="string"){const g=_=>{const y=_.width,v=_.height;if(i.isDisposed)return;const x=i==null?void 0:i.getEngine().resizeImageBitmap(_,y,v);m(x,y,v)};Me.LoadImage(e,g,t.onError?t.onError:()=>{},i.offlineProvider)}else m(e.data,e.width,e.height);return f}const V2t={CreateGround:aT,CreateGroundFromHeightMap:jJ,CreateTiledGround:HJ};at.CreateGround=P1;at.CreateTiledGround=Yge;at.CreateGroundFromHeightMap=Qge;Ee.CreateGround=(s,e,t,i,r,n)=>aT(s,{width:e,height:t,subdivisions:i,updatable:n},r);Ee.CreateTiledGround=(s,e,t,i,r,n,a,o,l)=>HJ(s,{xmin:e,zmin:t,xmax:i,zmax:r,subdivisions:n,precision:a,updatable:l},o);Ee.CreateGroundFromHeightMap=(s,e,t,i,r,n,a,o,l,c,u)=>jJ(s,e,{width:t,height:i,subdivisions:r,minHeight:n,maxHeight:a,updatable:l,onReady:c,alphaFilter:u},o);function XJ(s){const e=[],t=[],i=[],r=[],n=s.diameter||1,a=s.thickness||.5,o=(s.tessellation||16)|0,l=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,c=o+1;for(let h=0;h<=o;h++){const d=h/o,f=h*Math.PI*2/o-Math.PI/2,p=he.Translation(n/2,0,0).multiply(he.RotationY(f));for(let m=0;m<=o;m++){const g=1-m/o,_=m*Math.PI*2/o+Math.PI,y=Math.cos(_),v=Math.sin(_);let x=new D(y,v,0),A=x.scale(a/2);const b=new we(d,g);A=D.TransformCoordinates(A,p),x=D.TransformNormal(x,p),t.push(A.x,A.y,A.z),i.push(x.x,x.y,x.z),r.push(b.x,Qr?1-b.y:b.y);const C=(h+1)%c,T=(m+1)%c;e.push(h*c+m),e.push(h*c+T),e.push(C*c+m),e.push(h*c+T),e.push(C*c+T),e.push(C*c+m)}}at._ComputeSides(l,t,e,i,r,s.frontUVs,s.backUVs);const u=new at;return u.indices=e,u.positions=t,u.normals=i,u.uvs=r,u}function ug(s,e={},t){const i=new Ee(s,t);return e.sideOrientation=Ee._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,XJ(e).applyToMesh(i,e.updatable),i}const G2t={CreateTorus:ug};at.CreateTorus=XJ;Ee.CreateTorus=(s,e,t,i,r,n,a)=>ug(s,{diameter:e,thickness:t,tessellation:i,sideOrientation:a,updatable:n},r);class YJ{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=YJ._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=ug("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new et("targetMat",e);i.specularColor=Re.Black(),i.emissiveColor=new Re(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new $i(D.Zero(),new D(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}YJ._IdCounter=0;class TTe extends YJ{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new $i(D.Zero(),D.Forward())}}class W2t{}class t6{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new Ae,this.onAfterEnteringVRObservable=new Ae,this.onExitingVRObservable=new Ae,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=t6.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new D(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new D(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Re(.2,.2,1),this._pickedGazeColor=new Re(0,0,1),this.onNewMeshSelected=new Ae,this.onNewMeshPicked=new Ae,this.onBeforeCameraTeleport=new Ae,this.onAfterCameraTeleport=new Ae,this.onSelectedMeshUnselected=new Ae,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=r=>{r.type!==hl.POSE_ENABLED&&(r.leftStick&&r.onleftstickchanged(n=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(n,this._cameraGazer),this._checkTeleportBackwards(n,this._cameraGazer))}),r.rightStick&&r.onrightstickchanged(n=>{this._teleportationInitialized&&this._checkRotate(n,this._cameraGazer)}),r.type===hl.XBOX&&(r.onbuttondown(n=>{this._interactionsEnabled&&n===0&&this._cameraGazer._selectionPointerDown()}),r.onbuttonup(n=>{this._interactionsEnabled&&n===0&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=D.Zero(),this._workingQuaternion=Pe.Identity(),this._workingMatrix=he.Identity(),fe.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),!("getVRDisplays"in navigator)&&t.useXR===void 0&&(t.useXR=!0),t.createFallbackVRDeviceOrientationFreeCamera===void 0&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),t.createDeviceOrientationCamera===void 0&&(t.createDeviceOrientationCamera=!0),t.laserToggle===void 0&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new D(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new UJ("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof pa&&this._scene.activeCamera.rotation)){const r=this._scene.activeCamera;r.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(r.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(Pe.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z)),this._deviceOrientationCamera.rotation=r.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Dz.IsSessionSupportedAsync("immersive-vr").then(r=>{r?(fe.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(n=>{this.xr=n,this.xrTestDone=!0,this._cameraGazer=new TTe(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(a=>{switch(a){case 0:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case 1:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case 2:this._hasEnteredVR=!0;break;case 3:this._hasEnteredVR=!1;break}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new WJ("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new TTe(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let n=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";n+=".babylonVRicon.vrdisplaypresenting { display: none; }";const a=document.createElement("style");a.appendChild(document.createTextNode(n)),document.getElementsByTagName("head")[0].appendChild(a),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=r=>{r.keyCode===27&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},yt.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new x9e,this._circleEase.setEasingMode(ya.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(r=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&r.event.pointerType==="mouse"&&(r.type===yt.POINTERDOWN?this._cameraGazer._selectionPointerDown():r.type===yt.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===2||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){!this._useCustomVRButton&&!this._btnVRDisplayed&&this._btnVR&&(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){!this._btnVR||this._useCustomVRButton||(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){fe.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=Pe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){fe.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===2&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>this._isTeleportationFloor(e)||e.name.indexOf("gazeTracker")===-1&&e.name.indexOf("teleportationTarget")===-1&&e.name.indexOf("torusTeleportation")===-1?this.raySelectionPredicate(e):!1,this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);t!==-1&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const i=e.floorMeshes||[];if(!i.length){const r=this._scene.getMeshByName(e.floorMeshName);r&&i.push(r)}if(this.xr){i.forEach(r=>{this.xr.teleportation.addFloorMesh(r)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){const r=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(r),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(r);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),e.easingFunction!==void 0&&(this._teleportationEasing=e.easingFunction);const t=new lr;t.vignetteColor=new Ze(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const i=Pe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),r=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,Pe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),D.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const n=new $i(r,this._workingVector),a=this._scene.pickWithRay(n,this._raySelectionPredicate);a&&a.pickedPoint&&a.pickedMesh&&this._isTeleportationFloor(a.pickedMesh)&&a.distance<5&&this.teleportCamera(a.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=aT("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new Qf("DynamicTexture",e,this._scene,!0);t.hasAlpha=!0;const i=t.getContext(),r=e/2,n=e/2,a=200;i.beginPath(),i.arc(r,n,a,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();const o=new et("TextPlaneMaterial",this._scene);o.diffuseTexture=t,this._teleportationTarget.material=o;const l=ug("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const c=new tt("animationInnerCircle","position.y",30,tt.ANIMATIONTYPE_FLOAT,tt.ANIMATIONLOOPMODE_CYCLE),u=[];u.push({frame:0,value:0}),u.push({frame:30,value:.4}),u.push({frame:60,value:0}),c.setKeys(u);const h=new Age;h.setEasingMode(ya.EASINGMODE_EASEINOUT),c.setEasingFunction(h),l.animations=[],l.animations.push(c),this._scene.beginAnimation(l,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof Dl))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=Pe.FromRotationMatrix(he.RotationY(Math.PI/4*this._rotationAngle)),i=new tt("animationRotation","rotationQuaternion",90,tt.ANIMATIONTYPE_QUATERNION,tt.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const n=new tt("animationPP","vignetteWeight",90,tt.ANIMATIONTYPE_FLOAT,tt.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),n.setKeys(a),n.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(n);const o=new tt("animationPP2","vignetteStretch",90,tt.ANIMATIONTYPE_FLOAT,tt.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),o.setKeys(l),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof Dl))return;this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector);const t=90;let i,r;if(this._teleportationMode==t6.TELEPORTATIONMODE_CONSTANTSPEED){r=t;const d=D.Distance(this.currentVRCamera.position,this._workingVector);i=this._teleportationSpeed/d}else r=Math.round(this._teleportationTime*t/1e3),i=1;this.currentVRCamera.animations=[];const n=new tt("animationCameraTeleportation","position",t,tt.ANIMATIONTYPE_VECTOR3,tt.ANIMATIONLOOPMODE_CONSTANT),a=[{frame:0,value:this.currentVRCamera.position},{frame:r,value:this._workingVector}];n.setKeys(a),n.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];const o=Math.round(r/2),l=new tt("animationPP","vignetteWeight",t,tt.ANIMATIONTYPE_FLOAT,tt.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:o,value:8}),c.push({frame:r,value:0}),l.setKeys(c),this._postProcessMove.animations.push(l);const u=new tt("animationPP2","vignetteStretch",t,tt.ANIMATIONTYPE_FLOAT,tt.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:o,value:10}),h.push({frame:r,value:0}),u.setKeys(h),this._postProcessMove.animations.push(u),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,r,!1,i,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}t6.TELEPORTATIONMODE_CONSTANTTIME=0;t6.TELEPORTATIONMODE_CONSTANTSPEED=1;const K2t=(s,e,t,i)=>!(s.x>t.x+i||t.x-i>e.x||s.y>t.y+i||t.y-i>e.y||s.z>t.z+i||t.z-i>e.z),NI=function(){const s={root:0,found:!1};return function(e,t,i,r){s.root=0,s.found=!1;const n=t*t-4*e*i;if(n<0)return s;const a=Math.sqrt(n);let o=(-t-a)/(2*e),l=(-t+a)/(2*e);if(o>l){const c=l;l=o,o=c}return o>0&&o0&&l=0)}_canDoCollision(e,t,i,r){const n=D.Distance(this._basePointWorld,e),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(n>this._velocityWorldLength+a+t||!K2t(i,r,this._basePointWorld,this._velocityWorldLength+a))}_testTriangle(e,t,i,r,n,a,o){let l,c=!1;t||(t=[]),t[e]||(t[e]=new Xl(0,0,0,0),t[e].copyFromPoints(i,r,n));const u=t[e];if(!a&&!u.isFrontFacingTo(this._normalizedVelocity,0))return;const h=u.signedDistanceTo(this._basePoint),d=D.Dot(u.normal,this._velocity);if(Lz.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(h)>=1)return;c=!0,l=0}else{l=(-1-h)/d;let m=(1-h)/d;if(l>m){const g=m;m=l,l=g}if(l>1||m<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let f=!1,p=1;if(c||(this._basePoint.subtractToRef(u.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,n,u.normal)&&(f=!0,p=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let m=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let g=2*D.Dot(this._velocity,this._tempVector),_=this._tempVector.lengthSquared()-1,y=NI(m,g,_,p);y.found&&(p=y.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),g=2*D.Dot(this._velocity,this._tempVector),_=this._tempVector.lengthSquared()-1,y=NI(m,g,_,p),y.found&&(p=y.root,f=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(n,this._tempVector),g=2*D.Dot(this._velocity,this._tempVector),_=this._tempVector.lengthSquared()-1,y=NI(m,g,_,p),y.found&&(p=y.root,f=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let v=this._edge.lengthSquared(),x=D.Dot(this._edge,this._velocity),A=D.Dot(this._edge,this._baseToVertex);if(m=v*-this._velocitySquaredLength+x*x,g=2*(v*D.Dot(this._velocity,this._baseToVertex)-x*A),_=v*(1-this._baseToVertex.lengthSquared())+A*A,y=NI(m,g,_,p),y.found){const b=(x*y.root-A)/v;b>=0&&b<=1&&(p=y.root,f=!0,this._edge.scaleInPlace(b),i.addToRef(this._edge,this._collisionPoint))}if(n.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),v=this._edge.lengthSquared(),x=D.Dot(this._edge,this._velocity),A=D.Dot(this._edge,this._baseToVertex),m=v*-this._velocitySquaredLength+x*x,g=2*(v*D.Dot(this._velocity,this._baseToVertex)-x*A),_=v*(1-this._baseToVertex.lengthSquared())+A*A,y=NI(m,g,_,p),y.found){const b=(x*y.root-A)/v;b>=0&&b<=1&&(p=y.root,f=!0,this._edge.scaleInPlace(b),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),v=this._edge.lengthSquared(),x=D.Dot(this._edge,this._velocity),A=D.Dot(this._edge,this._baseToVertex),m=v*-this._velocitySquaredLength+x*x,g=2*(v*D.Dot(this._velocity,this._baseToVertex)-x*A),_=v*(1-this._baseToVertex.lengthSquared())+A*A,y=NI(m,g,_,p),y.found){const b=(x*y.root-A)/v;b>=0&&b<=1&&(p=y.root,f=!0,this._edge.scaleInPlace(b),n.addToRef(this._edge,this._collisionPoint))}}if(f){const m=p*p*this._velocitySquaredLength;(!this.collisionFound||m=r){n.copyFrom(e);return}const l=a?a.collisionMask:i.collisionMask;i._initialize(e,t,o);const c=a&&a.surroundingMeshes||this._scene.meshes;for(let u=0;unew bBe;const Pne={effect:null,subMesh:null};class na extends aa{constructor(e,t,i,r={},n=!0){super(e,t,n),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new he,this._cachedWorldViewProjectionMatrix=new he,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(t.length*16);for(let r=0;rn===e||n.startsWith(i));return r>=0&&this.options.defines.splice(r,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const A=r?i._drawWrapper:this._drawWrapper;if(A.effect&&A._wasPreviouslyReady&&A._wasPreviouslyUsingInstances===t)return!0}const n=this.getScene(),a=n.getEngine(),o=[],l=[],c=new oa;let u=this._shaderPath,h=this._options.uniforms,d=this._options.uniformBuffers,f=this._options.samplers;a.getCaps().multiview&&n.activeCamera&&n.activeCamera.outputRenderTarget&&n.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),h.indexOf("viewProjection")!==-1&&h.indexOf("viewProjectionR")===-1&&h.push("viewProjectionR"));for(let A=0;A4&&(l.push($.MatricesIndicesExtraKind),l.push($.MatricesWeightsExtraKind));const A=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),A.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),h.indexOf("boneTextureWidth")===-1&&h.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(A.bones.length+1)),h.indexOf("mBones")===-1&&h.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let p=0;const m=e?e.morphTargetManager:null;if(m){const A=m.supportsUVs&&o.indexOf("#define UV1")!==-1,b=m.supportsTangents&&o.indexOf("#define TANGENT")!==-1,C=m.supportsNormals&&o.indexOf("#define NORMAL")!==-1;p=m.numMaxInfluencers||m.numInfluencers,A&&o.push("#define MORPHTARGETS_UV"),b&&o.push("#define MORPHTARGETS_TANGENT"),C&&o.push("#define MORPHTARGETS_NORMAL"),p>0&&o.push("#define MORPHTARGETS"),m.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),h.indexOf("morphTargetTextureIndices")===-1&&h.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+p);for(let T=0;T0&&(h=h.slice(),h.push("morphTargetInfluences"),h.push("morphTargetCount"),h.push("morphTargetTextureInfo"),h.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const A=e.bakedVertexAnimationManager;A&&A.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),h.indexOf("bakedVertexAnimationSettings")===-1&&h.push("bakedVertexAnimationSettings"),h.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&h.push("bakedVertexAnimationTextureSizeInverted"),h.indexOf("bakedVertexAnimationTime")===-1&&h.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),Zw(l,e,o)}for(const A in this._textures)if(!this._textures[A].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(fo(h),t3(this,n,o)),n.fogEnabled&&(e!=null&&e.applyFog)&&n.fogMode!==gt.FOGMODE_NONE&&(o.push("#define FOG"),h.indexOf("view")===-1&&h.push("view"),h.indexOf("vFogInfos")===-1&&h.push("vFogInfos"),h.indexOf("vFogColor")===-1&&h.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),h.indexOf("logarithmicDepthConstant")===-1&&h.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(h=h.slice(),d=d.slice(),f=f.slice(),u=this.customShaderNameResolve(this.name,h,d,f,o,l));const g=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,_=(g==null?void 0:g.effect)??null,y=(g==null?void 0:g.defines)??null,v=o.join(` `);let x=_;return y!==v&&(x=a.createEffect(u,{attributes:l,uniformsNames:h,uniformBuffersNames:d,samplers:f,defines:v,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},a),r?i.setEffect(x,v,this._materialContext):g&&g.setEffect(x,v),this._onEffectCreatedObservable&&(Pne.effect=x,Pne.subMesh=i??(e==null?void 0:e.subMeshes[0])??null,this._onEffectCreatedObservable.notifyObservers(Pne))),g._wasPreviouslyUsingInstances=!!t,x!=null&&x.isReady()?(_!==x&&n.resetCachedMaterial(),g._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){const i=this.getScene(),r=t??this.getEffect();r&&(this._options.uniforms.indexOf("world")!==-1&&r.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),this._options.uniforms.indexOf("view")!==-1&&r.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var r;this.bind(e,t,(r=i._drawWrapperOverride)==null?void 0:r.effect,i)}bind(e,t,i,r){var h;const n=r&&this._storeEffectOnSubMeshes,a=i??(n?r.effect:this.getEffect());if(!a)return;const o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let c=!1;if(a&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let d=0;d0&&I0(t,a);const f=t.bakedVertexAnimationManager;if(f&&f.isEnabled){const p=n?r._drawWrapper:this._drawWrapper;(h=t.bakedVertexAnimationManager)==null||h.bind(a,!!p._wasPreviouslyUsingInstances)}}this._afterBind(t,a,r)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let r=0;rnew na(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach(i=>{const r=this._options[i];Array.isArray(r)&&(this._options[i]=r.slice(0))}),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let r;for(r in this._textures)this._textures[r].dispose();for(r in this._textureArrays){const n=this._textureArrays[r];for(let a=0;anew na(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let n;e.stencil&&r.stencil.parse(e.stencil,t,i);for(n in e.textures)r.setTexture(n,xe.Parse(e.textures[n],t,i));for(n in e.textureArrays){const a=e.textureArrays[n],o=[];for(let l=0;l(c%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>Re.FromArray(o));r.setColor3Array(n,a)}for(n in e.colors4)r.setColor4(n,Ze.FromArray(e.colors4[n]));for(n in e.colors4Arrays){const a=e.colors4Arrays[n].reduce((o,l,c)=>(c%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>Ze.FromArray(o));r.setColor4Array(n,a)}for(n in e.vectors2)r.setVector2(n,we.FromArray(e.vectors2[n]));for(n in e.vectors3)r.setVector3(n,D.FromArray(e.vectors3[n]));for(n in e.vectors4)r.setVector4(n,mt.FromArray(e.vectors4[n]));for(n in e.quaternions)r.setQuaternion(n,Pe.FromArray(e.quaternions[n]));for(n in e.matrices)r.setMatrix(n,he.FromArray(e.matrices[n]));for(n in e.matrixArray)r._matrixArrays[n]=new Float32Array(e.matrixArray[n]);for(n in e.matrices3x3)r.setMatrix3x3(n,e.matrices3x3[n]);for(n in e.matrices2x2)r.setMatrix2x2(n,e.matrices2x2[n]);for(n in e.vectors2Arrays)r.setArray2(n,e.vectors2Arrays[n]);for(n in e.vectors3Arrays)r.setArray3(n,e.vectors3Arrays[n]);for(n in e.vectors4Arrays)r.setArray4(n,e.vectors4Arrays[n]);for(n in e.quaternionsArrays)r.setArray4(n,e.quaternionsArrays[n]);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise((n,a)=>{const o=new On;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),c=this.Parse(l,i||Rt.LastCreatedScene,r);e&&(c.name=e),n(c)}else a("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,n)=>{const a=new On;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),c=this.Parse(l,t||Rt.LastCreatedScene,i);c.snippetId=e,r(c)}else n("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}na.SnippetUrl="https://snippet.babylonjs.com";na.CreateFromSnippetAsync=na.ParseFromSnippetAsync;ve("BABYLON.ShaderMaterial",na);class H2t{constructor(){this._pickingTexture=null,this._idMap=[],this._thinIdMap=[],this._idColors=[],this._meshMaterialMap=new Map,this._meshRenderingCount=0,this._attributeName="instanceMeshID",this._shaderLanguage=0}get shaderLanguage(){return this._shaderLanguage}_createRenderTarget(e,t,i){this._pickingTexture&&this._pickingTexture.dispose(),this._pickingTexture=new Rs("pickingTexure",{width:t,height:i},e,!1,void 0,0,!1,1)}async _createColorMaterialAsync(e){this._defaultRenderMaterial&&this._defaultRenderMaterial.dispose(),this._defaultRenderMaterial=null,e.getEngine().isWebGPU&&(this._shaderLanguage=1);const i=[],r={attributes:[$.PositionKind,this._attributeName,"bakedVertexAnimationSettingsInstanced"],uniforms:["world","viewProjection","meshID"],needAlphaBlending:!1,defines:i,useClipPlane:null,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this.shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>lvt),void 0),Ue(()=>Promise.resolve().then(()=>Cvt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>j2t),void 0),Ue(()=>Promise.resolve().then(()=>ovt),void 0)])}};this._defaultRenderMaterial=new na("pickingShader",e,"picking",r,!1),this._defaultRenderMaterial.onBindObservable.add(this._materialBindCallback,void 0,void 0,this)}_materialBindCallback(e){if(!e)return;const i=this._meshMaterialMap.get(e).getEffect();!e.hasInstances&&!e.isAnInstance&&!e.hasThinInstances&&i.setColor4("meshID",this._idColors[e.uniqueId],1),this._meshRenderingCount++}_generateColorData(e,t,i,r,n,a,o){const l=new Float32Array(4*(e+1));l[0]=r/255,l[1]=n/255,l[2]=a/255,l[3]=1;for(let c=0;c>16,h=(t&65280)>>8,d=(t&255)>>0;o(c,t),l[(c+1)*4]=u/255,l[(c+1)*4+1]=h/255,l[(c+1)*4+2]=d/255,l[(c+1)*4+3]=1,t++}return l}_generateThinInstanceColorData(e,t,i){const r=new Float32Array(4*e);for(let n=0;n>16,o=(t&65280)>>8,l=(t&255)>>0;i(n,t),r[n*4]=a/255,r[n*4+1]=o/255,r[n*4+2]=l/255,r[n*4+3]=1,t++}return r}setPickingList(e){if(this._pickableMeshes){for(let o=0;o>16,h=(a&65280)>>8,d=(a&255)>>0;if(l.hasThinInstances){const f=this._generateThinInstanceColorData(l.thinInstanceCount,a,(p,m)=>{this._thinIdMap[m]={meshId:o,thinId:p}});a+=l.thinInstanceCount,l.thinInstanceSetBuffer(this._attributeName,f,4)}else if(this._idMap[a]=o,a++,l.hasInstances){const f=l.instances,p=this._generateColorData(f.length,a,o,u,h,d,(_,y)=>{const v=f[_];this._idMap[y]=this._pickableMeshes.indexOf(v)});a+=f.length;const m=l.getEngine(),g=new $(m,p,this._attributeName,!1,!1,4,!0);l.setVerticesBuffer(g,!0)}else this._idColors[l.uniqueId]=Re.FromInts(u,h,d)}}async pickAsync(e,t,i=!1){if(!this._pickableMeshes||this._pickableMeshes.length===0)return Promise.resolve(null);const r=this._cachedScene,n=r.getEngine(),a=n.getRenderWidth(),o=n.getRenderHeight(),l=1/n._hardwareScalingLevel;if(this._meshRenderingCount=0,e=l*e>>0,t=l*t>>0,e<0||t<0||e>=a||t>=o)return Promise.resolve(null);this._readbuffer||(this._readbuffer=new Uint8Array(n.isWebGPU?256:4)),t=o-t,this._pickingTexture.clearColor=new Ze(0,0,0,0),this._pickingTexture.onBeforeRender=()=>{n.enableScissor&&n.enableScissor(e,t,1,1)},r.customRenderTargets.push(this._pickingTexture);const c=this._pickingTexture.getSize();if(c.width!==a||c.height!==o){this._createRenderTarget(r,a,o),this._pickingTexture.renderList=[];for(let u=0;u{this._pickingTexture.onAfterRender=async()=>{n.disableScissor&&n.disableScissor(),this._pickingTexture||h();let d=null,f;const p=this._meshRenderingCount>0;if(p){const m=r.customRenderTargets.indexOf(this._pickingTexture);if(m>-1&&r.customRenderTargets.splice(m,1),await this._readTexturePixelsAsync(e,t)){const g=this._readbuffer[0],_=this._readbuffer[1],y=this._readbuffer[2],v=(g<<16)+(_<<8)+y;this._thinIdMap[v]?(d=this._pickableMeshes[this._thinIdMap[v].meshId],f=this._thinIdMap[v].thinId):d=this._pickableMeshes[this._idMap[v]]}}if(p)i&&this.dispose(),u(d?{mesh:d,thinInstanceIndex:f}:null);else{this._meshRenderingCount=0;return}}})}async _readTexturePixelsAsync(e,t){var r;return!this._cachedScene||!((r=this._pickingTexture)!=null&&r._texture)?!1:(await this._cachedScene.getEngine()._readTexturePixels(this._pickingTexture._texture,1,1,-1,0,this._readbuffer,!0,!0,e,t),!0)}dispose(){var e,t;this.setPickingList(null),this._cachedScene=null,(e=this._pickingTexture)==null||e.dispose(),this._pickingTexture=null,(t=this._defaultRenderMaterial)==null||t.dispose(),this._defaultRenderMaterial=null}}const CBe="pickingPixelShader",SBe=`#if defined(INSTANCES) varying vec4 vMeshID; #else uniform vec4 meshID; #endif void main(void) { #if defined(INSTANCES) gl_FragColor=vMeshID; #else gl_FragColor=meshID; #endif }`;de.ShadersStore[CBe]=SBe;const EBe={name:CBe,shader:SBe},j2t=Object.freeze(Object.defineProperty({__proto__:null,pickingPixelShader:EBe},Symbol.toStringTag,{value:"Module"})),TBe="bonesDeclaration",MBe=`#if NUM_BONE_INFLUENCERS>0 attribute vec4 matricesIndices;attribute vec4 matricesWeights; #if NUM_BONE_INFLUENCERS>4 attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; #endif #ifndef BAKED_VERTEX_ANIMATION_TEXTURE #ifdef BONETEXTURE uniform highp sampler2D boneSampler;uniform float boneTextureWidth; #else uniform mat4 mBones[BonesPerMesh]; #endif #ifdef BONES_VELOCITY_ENABLED uniform mat4 mPreviousBones[BonesPerMesh]; #endif #ifdef BONETEXTURE #define inline mat4 readMatrixFromRawSampler(sampler2D smp,float index) {float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} #endif #endif #endif `;de.IncludesShadersStore[TBe]=MBe;const RBe={name:TBe,shader:MBe},X2t=Object.freeze(Object.defineProperty({__proto__:null,bonesDeclaration:RBe},Symbol.toStringTag,{value:"Module"})),Y2t="bakedVertexAnimationDeclaration",Q2t=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; #ifdef INSTANCES attribute vec4 bakedVertexAnimationSettingsInstanced; #endif #define inline mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) {float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} #endif `;de.IncludesShadersStore[Y2t]=Q2t;const IBe="morphTargetsVertexGlobalDeclaration",PBe=`#ifdef MORPHTARGETS uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; #ifdef MORPHTARGETS_TEXTURE uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) { float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} #endif #endif `;de.IncludesShadersStore[IBe]=PBe;const wBe={name:IBe,shader:PBe},$2t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalDeclaration:wBe},Symbol.toStringTag,{value:"Module"})),DBe="morphTargetsVertexDeclaration",LBe=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE attribute vec3 position{X}; #ifdef MORPHTARGETS_NORMAL attribute vec3 normal{X}; #endif #ifdef MORPHTARGETS_TANGENT attribute vec3 tangent{X}; #endif #ifdef MORPHTARGETS_UV attribute vec2 uv_{X}; #endif #elif {X}==0 uniform int morphTargetCount; #endif #endif `;de.IncludesShadersStore[DBe]=LBe;const OBe={name:DBe,shader:LBe},Z2t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexDeclaration:OBe},Symbol.toStringTag,{value:"Module"})),q2t="instancesDeclaration",J2t=`#ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #ifdef INSTANCESCOLOR attribute vec4 instanceColor; #endif #if defined(THIN_INSTANCES) && !defined(WORLD_UBO) uniform mat4 world; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; #ifdef THIN_INSTANCES uniform mat4 previousWorld; #endif #endif #else #if !defined(WORLD_UBO) uniform mat4 world; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) uniform mat4 previousWorld; #endif #endif `;de.IncludesShadersStore[q2t]=J2t;const NBe="morphTargetsVertexGlobal",FBe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE float vertexID; #endif #endif `;de.IncludesShadersStore[NBe]=FBe;const BBe={name:NBe,shader:FBe},evt=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobal:BBe},Symbol.toStringTag,{value:"Module"})),kBe="morphTargetsVertex",UBe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0; #ifdef MORPHTARGETS_NORMAL normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0; #endif #ifdef MORPHTARGETS_UV uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i]; #endif } #endif #else positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; #ifdef MORPHTARGETS_NORMAL normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_UV uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; #endif #endif #endif `;de.IncludesShadersStore[kBe]=UBe;const zBe={name:kBe,shader:UBe},tvt=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertex:zBe},Symbol.toStringTag,{value:"Module"})),ivt="instancesVertex",rvt=`#ifdef INSTANCES mat4 finalWorld=mat4(world0,world1,world2,world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); #endif #ifdef THIN_INSTANCES finalWorld=world*finalWorld; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) finalPreviousWorld=previousWorld*finalPreviousWorld; #endif #endif #else mat4 finalWorld=world; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) mat4 finalPreviousWorld=previousWorld; #endif #endif `;de.IncludesShadersStore[ivt]=rvt;const VBe="bonesVertex",GBe=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 mat4 influence; #ifdef BONETEXTURE influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; #endif #else influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif #endif finalWorld=finalWorld*influence; #endif #endif `;de.IncludesShadersStore[VBe]=GBe;const WBe={name:VBe,shader:GBe},svt=Object.freeze(Object.defineProperty({__proto__:null,bonesVertex:WBe},Symbol.toStringTag,{value:"Module"})),nvt="bakedVertexAnimation",avt=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES #define BVASNAME bakedVertexAnimationSettingsInstanced #else #define BVASNAME bakedVertexAnimationSettings #endif float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; #endif finalWorld=finalWorld*VATInfluence;} #endif `;de.IncludesShadersStore[nvt]=avt;const KBe="pickingVertexShader",HBe=`attribute vec3 position; #if defined(INSTANCES) attribute vec4 instanceMeshID; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #include uniform mat4 viewProjection; #if defined(INSTANCES) varying vec4 vMeshID; #endif void main(void) { #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos; #if defined(INSTANCES) vMeshID=instanceMeshID; #endif }`;de.ShadersStore[KBe]=HBe;const jBe={name:KBe,shader:HBe},ovt=Object.freeze(Object.defineProperty({__proto__:null,pickingVertexShader:jBe},Symbol.toStringTag,{value:"Module"})),XBe="pickingPixelShader",YBe=`#if defined(INSTANCES) varying vMeshID: vec4f; #else uniform meshID: vec4f; #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #if defined(INSTANCES) fragmentOutputs.color=input.vMeshID; #else fragmentOutputs.color=uniforms.meshID; #endif }`;de.ShadersStoreWGSL[XBe]=YBe;const QBe={name:XBe,shader:YBe},lvt=Object.freeze(Object.defineProperty({__proto__:null,pickingPixelShaderWGSL:QBe},Symbol.toStringTag,{value:"Module"})),$Be="bonesDeclaration",ZBe=`#if NUM_BONE_INFLUENCERS>0 attribute matricesIndices : vec4;attribute matricesWeights : vec4; #if NUM_BONE_INFLUENCERS>4 attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; #endif #ifndef BAKED_VERTEX_ANIMATION_TEXTURE #ifdef BONETEXTURE var boneSampler : texture_2d;uniform boneTextureWidth : f32; #else uniform mBones : array; #ifdef BONES_VELOCITY_ENABLED uniform mPreviousBones : array; #endif #endif #ifdef BONETEXTURE fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 {let offset=i32(index) *4; let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} #endif #endif #endif `;de.IncludesShadersStoreWGSL[$Be]=ZBe;const qBe={name:$Be,shader:ZBe},cvt=Object.freeze(Object.defineProperty({__proto__:null,bonesDeclarationWGSL:qBe},Symbol.toStringTag,{value:"Module"})),uvt="bakedVertexAnimationDeclaration",hvt=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; #ifdef INSTANCES attribute bakedVertexAnimationSettingsInstanced : vec4; #endif fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 {let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} #endif `;de.IncludesShadersStoreWGSL[uvt]=hvt;const JBe="morphTargetsVertexGlobalDeclaration",eke=`#ifdef MORPHTARGETS uniform morphTargetInfluences : array; #ifdef MORPHTARGETS_TEXTURE uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 { let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} #endif #endif `;de.IncludesShadersStoreWGSL[JBe]=eke;const tke={name:JBe,shader:eke},dvt=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalDeclarationWGSL:tke},Symbol.toStringTag,{value:"Module"})),ike="morphTargetsVertexDeclaration",rke=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE attribute position{X} : vec3; #ifdef MORPHTARGETS_NORMAL attribute normal{X} : vec3; #endif #ifdef MORPHTARGETS_TANGENT attribute tangent{X} : vec3; #endif #ifdef MORPHTARGETS_UV attribute uv_{X} : vec2; #endif #elif {X}==0 uniform morphTargetCount: i32; #endif #endif `;de.IncludesShadersStoreWGSL[ike]=rke;const ske={name:ike,shader:rke},fvt=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexDeclarationWGSL:ske},Symbol.toStringTag,{value:"Module"})),pvt="instancesDeclaration",mvt=`#ifdef INSTANCES attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; #ifdef INSTANCESCOLOR attribute instanceColor : vec4; #endif #if defined(THIN_INSTANCES) && !defined(WORLD_UBO) uniform world : mat4x4; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; #ifdef THIN_INSTANCES uniform previousWorld : mat4x4; #endif #endif #else #if !defined(WORLD_UBO) uniform world : mat4x4; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) uniform previousWorld : mat4x4; #endif #endif `;de.IncludesShadersStoreWGSL[pvt]=mvt;const nke="morphTargetsVertexGlobal",ake=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE var vertexID : f32; #endif #endif `;de.IncludesShadersStoreWGSL[nke]=ake;const oke={name:nke,shader:ake},gvt=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalWGSL:oke},Symbol.toStringTag,{value:"Module"})),lke="morphTargetsVertex",cke=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (var i=0; i=uniforms.morphTargetCount) {break;} vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0; #ifdef MORPHTARGETS_NORMAL normalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_UV uvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a); #endif } #endif #else positionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; #ifdef MORPHTARGETS_NORMAL normalUpdated+=(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a); #endif #ifdef MORPHTARGETS_UV uvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; #endif #endif #endif `;de.IncludesShadersStoreWGSL[lke]=cke;const uke={name:lke,shader:cke},_vt=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexWGSL:uke},Symbol.toStringTag,{value:"Module"})),vvt="instancesVertex",yvt=`#ifdef INSTANCES var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) var finalPreviousWorld=mat4x4(vertexInputs.previousWorld0,vertexInputs.previousWorld1,vertexInputs.previousWorld2,vertexInputs.previousWorld3); #endif #ifdef THIN_INSTANCES #if !defined(WORLD_UBO) finalWorld=uniforms.world*finalWorld; #else finalWorld=mesh.world*finalWorld; #endif #if defined(PREPASS_VELOCITY) || defined(VELOCITY) finalPreviousWorld=uniforms.previousWorld*finalPreviousWorld; #endif #endif #else #if !defined(WORLD_UBO) var finalWorld=uniforms.world; #else var finalWorld=mesh.world; #endif #if defined(PREPASS_VELOCITY) || defined(VELOCITY) var finalPreviousWorld=uniforms.previousWorld; #endif #endif `;de.IncludesShadersStoreWGSL[vvt]=yvt;const hke="bonesVertex",dke=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 var influence : mat4x4; #ifdef BONETEXTURE influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; #endif #else influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; #endif #endif finalWorld=finalWorld*influence; #endif #endif `;de.IncludesShadersStoreWGSL[hke]=dke;const fke={name:hke,shader:dke},xvt=Object.freeze(Object.defineProperty({__proto__:null,bonesVertexWGSL:fke},Symbol.toStringTag,{value:"Module"})),Avt="bakedVertexAnimation",bvt=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; #else let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; #endif let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; #endif finalWorld=finalWorld*VATInfluence;} #endif `;de.IncludesShadersStoreWGSL[Avt]=bvt;const pke="pickingVertexShader",mke=`attribute position: vec3f; #if defined(INSTANCES) attribute instanceMeshID: vec4f; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #include uniform viewProjection: mat4x4f; #if defined(INSTANCES) varying vMeshID: vec4f; #endif @vertex fn main(input : VertexInputs)->FragmentInputs { #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld*vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; #if defined(INSTANCES) vertexOutputs.vMeshID=input.instanceMeshID; #endif }`;de.ShadersStoreWGSL[pke]=mke;const gke={name:pke,shader:mke},Cvt=Object.freeze(Object.defineProperty({__proto__:null,pickingVertexShaderWGSL:gke},Symbol.toStringTag,{value:"Module"}));class i6{constructor(e,t,i,r=""){this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Ae,this.onErrorObservable=new Ae,this.onBindObservable=new Ae,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=1,this.name=e,this._key=r,this._engine=i,this.uniqueId=i6._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=de.GetShadersStore(this._shaderLanguage),this._shaderRepository=de.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=de.GetIncludesShadersStore(this._shaderLanguage);let n;const a=To()?this._engine.getHostDocument():null;typeof e=="string"?n=e:e.computeSource?n="source:"+e.computeSource:e.computeElement?n=(a==null?void 0:a.getElementById(e.computeElement))||e.computeElement:n=e.compute||e;const o={defines:this.defines.split(` `),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:(l,c,u)=>{if(!u)return c;for(const h of u){const f=h.replace("#define","").replace(";","").trim().split(" ");if(f.length===2){const p=f[0],m=f[1];(!isNaN(parseInt(m))||!isNaN(parseFloat(m)))&&(c=`const ${p} = ${m}; `+c)}}return c}};this._loadShader(n,"Compute","",l=>{oge(o),g_t(l,o,c=>{this._rawComputeSourceCode=l,t.processFinalCode&&(c=t.processFinalCode(c));const u=lge(c,"",o);this._useFinalCode(u.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+` `+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const a=az(e);r(a);return}if(e.substr(0,7)==="source:"){r(e.substr(7));return}if(e.substr(0,7)==="base64:"){const a=window.atob(e.substr(7));r(a);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}let n;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?n=e:n=this._shaderRepository+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){var e;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getComputeShaderCode())??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,r=>{if(r&&r.numErrors>0){this._processCompilationErrors(r,t);return}this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_processCompilationErrors(e,t=null){var i;if(this._compilationError="",fe.Error("Unable to compile compute effect:"),this.defines&&fe.Error(`Defines: `+this.defines),i6.LogShaderCodeOnCompilationError){const r=(i=this._pipelineContext)==null?void 0:i._getComputeShaderCode();r&&(fe.Error("Compute code:"),fe.Error(r))}if(typeof e=="string")this._compilationError=e,fe.Error("Error: "+this._compilationError);else for(const r of e.messages){let n="";r.line!==void 0&&(n+="Line "+r.line+", "),r.offset!==void 0&&(n+="Offset "+r.offset+", "),r.length!==void 0&&(n+="Length "+r.length+", "),n+=r.type+": "+r.text,this._compilationError&&(this._compilationError+=` `),this._compilationError+=n,fe.Error(n)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){de.GetShadersStore(1)[`${e}ComputeShader`]=t}}i6._UniqueIdSeed=0;i6.LogShaderCodeOnCompilationError=!0;class $ge{constructor(){this._gpuTimeInFrameId=-1,this.counter=new io}_addDuration(e,t){e{const a=()=>{this.dispatch(e,t,i)?n():setTimeout(a,r)};a()})}serialize(){const e=qe.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],r=i.object;switch(i.type){case 0:case 4:case 1:{const n=r.serialize();n&&(e.textures[t]=n,e.bindings[t]={type:i.type});break}}}return e}static Parse(e,t,i){const r=qe.Parse(()=>new Hm(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const n in e.textures){const a=e.bindings[n],o=xe.Parse(e.textures[n],t,i);a.type===0?r.setTexture(n,o):a.type===4?r.setTexture(n,o,!1):r.setStorageTexture(n,o)}return r}static _BufferIsDataBuffer(e){return e.underlyingResource!==void 0}}F([X()],Hm.prototype,"name",void 0);F([X()],Hm.prototype,"fastMode",void 0);ve("BABYLON.ComputeShader",Hm);class Svt{constructor(e){this._engine=e}async _initializePlatform(){if(!this._platform)if(this._engine.getCaps().supportComputeShaders){const e=await Ue(()=>Promise.resolve().then(()=>Dvt),void 0);this._platform=new e.ComputeShaderBoundingHelper(this._engine)}else if(this._engine.getCaps().supportTransformFeedbacks){const e=await Ue(()=>Promise.resolve().then(()=>Ivt),void 0);this._platform=new e.TransformFeedbackBoundingHelper(this._engine)}else throw new Error("Your engine does not support Compute Shaders or Transform Feedbacks")}async computeAsync(e){return await this._initializePlatform(),this._platform.processAsync(e)}async batchInitializeAsync(e){return await this._initializePlatform(),this._platform.registerMeshListAsync(e)}batchProcess(){this._platform.processMeshList()}async batchFetchResultsAsync(){return this._platform.fetchResultsForMeshListAsync()}dispose(){this._platform.dispose()}}const Evt="gpuTransformVertexShader",Tvt=`attribute vec3 position; #include #include #include #include[0..maxSimultaneousMorphTargets] out vec3 outPosition;const mat4 identity=mat4( vec4(1.0,0.0,0.0,0.0), vec4(0.0,1.0,0.0,0.0), vec4(0.0,0.0,1.0,0.0), vec4(0.0,0.0,0.0,1.0) );void main(void) {vec3 positionUpdated=position; #include #include[0..maxSimultaneousMorphTargets] mat4 finalWorld=identity; #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);outPosition=worldPos.xyz;}`;de.ShadersStore[Evt]=Tvt;const Mvt="gpuTransformPixelShader",Rvt=`#version 300 es void main() {discard;} `;de.ShadersStore[Mvt]=Rvt;class uv{constructor(e){this._buffers={},this._effects={},this._meshListCounter=0,this._engine=e}processAsync(e){return Array.isArray(e)||(e=[e]),this._meshListCounter=0,this._processMeshList(e),Promise.resolve()}_processMeshList(e){const t=this._engine.getCaps().parallelShaderCompile;this._engine.getCaps().parallelShaderCompile=void 0;for(let i=0;i4&&(u.push($.MatricesIndicesExtraKind),u.push($.MatricesWeightsExtraKind));const m=r.skeleton;l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),m.isUsingTextureForMatrices?(l.push("#define BONETEXTURE"),c.indexOf("boneTextureWidth")===-1&&c.push("boneTextureWidth"),h.indexOf("boneSampler")===-1&&h.push("boneSampler")):(l.push("#define BonesPerMesh "+(m.bones.length+1)),c.indexOf("mBones")===-1&&c.push("mBones"))}else l.push("#define NUM_BONE_INFLUENCERS 0");const d=r?r.morphTargetManager:null;if(d){o=d.numMaxInfluencers||d.numInfluencers,o>0&&l.push("#define MORPHTARGETS"),d.isUsingTextureForTargets&&(l.push("#define MORPHTARGETS_TEXTURE"),c.indexOf("morphTargetTextureIndices")===-1&&c.push("morphTargetTextureIndices"),h.indexOf("morphTargets")===-1&&h.push("morphTargets")),l.push("#define NUM_MORPH_INFLUENCERS "+o);for(let m=0;m0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}const f=r.bakedVertexAnimationManager;f&&f.isEnabled&&(l.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),c.indexOf("bakedVertexAnimationSettings")===-1&&c.push("bakedVertexAnimationSettings"),c.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&c.push("bakedVertexAnimationTextureSizeInverted"),c.indexOf("bakedVertexAnimationTime")===-1&&c.push("bakedVertexAnimationTime"),h.indexOf("bakedVertexAnimationTexture")===-1&&h.push("bakedVertexAnimationTexture"),Zw(u,r,l));const p=l.join(` `);if(this._effects[p])a=this._effects[p];else{const m={attributes:u,uniformsNames:c,uniformBuffersNames:[],samplers:h,defines:p,fallbacks:null,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:o},maxSimultaneousLights:0,transformFeedbackVaryings:["outPosition"]};a=this._engine.createEffect("gpuTransform",m,this._engine),this._effects[p]=a}this._compute(r,a)}this._engine.getCaps().parallelShaderCompile=t}_compute(e,t){var c;const i=this._engine;let r;const n=e.getTotalVertices();if(this._buffers[e.uniqueId])r=this._buffers[e.uniqueId];else{const u=new Float32Array(n*3);r=new Mo(e.getEngine(),u,!0,3),this._buffers[e.uniqueId]=r}t.getEngine().enableEffect(t),e._bindDirect(t,null,!0),ql(e,t);const a=e.morphTargetManager;a&&a.numInfluencers>0&&I0(e,t);const o=e.bakedVertexAnimationManager;o&&o.isEnabled&&((c=e.bakedVertexAnimationManager)==null||c.bind(t,!1));const l=r.getData();if(i.bindTransformFeedbackBuffer(r.getBuffer()),i.setRasterizerState(!1),i.beginTransformFeedback(!0),i.drawArraysType(2,0,n),i.endTransformFeedback(),i.setRasterizerState(!0),i.readTransformFeedbackBuffer(l),i.bindTransformFeedbackBuffer(null),this._meshListCounter===0)e._refreshBoundingInfo(l,null);else{const u=e.getBoundingInfo().boundingBox,h=JS(l,0,n);uv._Min.copyFrom(u.minimum).minimizeInPlace(h.minimum),uv._Max.copyFrom(u.maximum).maximizeInPlace(h.maximum),e._refreshBoundingInfoDirect({minimum:uv._Min,maximum:uv._Max})}}registerMeshListAsync(e){return Array.isArray(e)||(e=[e]),this._meshList=e,this._meshListCounter=0,Promise.resolve()}processMeshList(){this._meshList.length!==0&&(this._processMeshList(this._meshList),this._meshListCounter++)}fetchResultsForMeshListAsync(){return this._meshListCounter=0,Promise.resolve()}dispose(){for(const e in this._buffers)this._buffers[e].dispose();this._buffers={},this._effects={},this._engine=null}}uv._Min=new D;uv._Max=new D;const Ivt=Object.freeze(Object.defineProperty({__proto__:null,TransformFeedbackBoundingHelper:uv},Symbol.toStringTag,{value:"Module"})),Pvt="boundingInfoComputeShader",wvt=`struct Results {minX : atomic, minY : atomic, minZ : atomic, maxX : atomic, maxY : atomic, maxZ : atomic, dummy1 : i32, dummy2 : i32,};fn floatToBits(value: f32)->i32 {return bitcast(value);} fn bitsToFloat(value: i32)->f32 {return bitcast(value);} fn atomicMinFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value>=oldValue) {break;} if (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}} fn atomicMaxFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value<=oldValue) {break;} if (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}} fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 {let offset=i32(index) *4; let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} const identity=mat4x4f( vec4f(1.0,0.0,0.0,0.0), vec4f(0.0,1.0,0.0,0.0), vec4f(0.0,0.0,1.0,0.0), vec4f(0.0,0.0,0.0,1.0) );struct Settings {morphTargetTextureInfo: vec3f, morphTargetCount: i32, indexResult : u32,};@group(0) @binding(0) var positionBuffer : array;@group(0) @binding(1) var resultBuffer : array;@group(0) @binding(7) var settings : Settings; #if NUM_BONE_INFLUENCERS>0 @group(0) @binding(2) var boneSampler : texture_2d;@group(0) @binding(3) var indexBuffer : array;@group(0) @binding(4) var weightBuffer : array; #if NUM_BONE_INFLUENCERS>4 @group(0) @binding(5) var indexExtraBuffer : array;@group(0) @binding(6) var weightExtraBuffer : array; #endif #endif #ifdef MORPHTARGETS @group(0) @binding(8) var morphTargets : texture_2d_array;@group(0) @binding(9) var morphTargetInfluences : array;@group(0) @binding(10) var morphTargetTextureIndices : array; #endif #ifdef MORPHTARGETS fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec3f { let vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0).xyz;} #endif @compute @workgroup_size(256,1,1) fn main(@builtin(global_invocation_id) global_id : vec3) {let index=global_id.x;if (index>=arrayLength(&positionBuffer)/3) {return;} let position=vec3f(positionBuffer[index*3],positionBuffer[index*3+1],positionBuffer[index*3+2]);var finalWorld=identity;var positionUpdated=position; #if NUM_BONE_INFLUENCERS>0 var influence : mat4x4;let matricesIndices=indexBuffer[index];let matricesWeights=weightBuffer[index];influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 let matricesIndicesExtra=indexExtraBuffer[index];let matricesWeightsExtra=weightExtraBuffer[index];influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.x)*matricesWeightsExtra.x; #if NUM_BONE_INFLUENCERS>5 influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.y)*matricesWeightsExtra.y; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.z)*matricesWeightsExtra.z; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.w)*matricesWeightsExtra.w; #endif #endif finalWorld=finalWorld*influence; #endif #ifdef MORPHTARGETS for (var i=0; i=settings.morphTargetCount) {break;} positionUpdated=positionUpdated+(readVector3FromRawSampler(i,index)-position)*morphTargetInfluences[i];} #endif var worldPos=finalWorld*vec4f(positionUpdated.x,positionUpdated.y,positionUpdated.z,1.0);atomicMinFloat(&resultBuffer[settings.indexResult].minX,worldPos.x);atomicMinFloat(&resultBuffer[settings.indexResult].minY,worldPos.y);atomicMinFloat(&resultBuffer[settings.indexResult].minZ,worldPos.z);atomicMaxFloat(&resultBuffer[settings.indexResult].maxX,worldPos.x);atomicMaxFloat(&resultBuffer[settings.indexResult].maxY,worldPos.y);atomicMaxFloat(&resultBuffer[settings.indexResult].maxZ,worldPos.z);} `;de.ShadersStoreWGSL[Pvt]=wvt;class _ke{constructor(e){this._computeShadersCache={},this._positionBuffers={},this._indexBuffers={},this._weightBuffers={},this._indexExtraBuffers={},this._weightExtraBuffers={},this._morphTargetInfluenceBuffers={},this._morphTargetTextureIndexBuffers={},this._ubos=[],this._uboIndex=0,this._processedMeshes=[],this._computeShaders=[],this._uniqueComputeShaders=new Set,this._resultBuffers=[],this._engine=e}_getComputeShader(e,t,i){let r;const n=e.join(` `);if(this._computeShadersCache[n])r=this._computeShadersCache[n];else{const a={positionBuffer:{group:0,binding:0},resultBuffer:{group:0,binding:1},settings:{group:0,binding:7}};t&&(a.boneSampler={group:0,binding:2},a.indexBuffer={group:0,binding:3},a.weightBuffer={group:0,binding:4},a.indexExtraBuffer={group:0,binding:5},a.weightExtraBuffer={group:0,binding:6}),i&&(a.morphTargets={group:0,binding:8},a.morphTargetInfluences={group:0,binding:9},a.morphTargetTextureIndices={group:0,binding:10}),r=new Hm(`boundingInfoCompute${t?"_bones":""}${i?"_morphs":""}`,this._engine,"boundingInfo",{bindingsMapping:a,defines:e}),this._computeShadersCache[n]=r}return r}_getUBO(){if(this._uboIndex>=this._ubos.length){const e=new zt(this._engine);e.addFloat3("morphTargetTextureInfo",0,0,0),e.addUniform("morphTargetCount",1),e.addUniform("indexResult",1),this._ubos.push(e)}return this._ubos[this._uboIndex++]}_extractDataAndLink(e,t,i,r,n,a){var c;let o;const l=t.getTotalVertices();if(a[t.uniqueId])o=a[t.uniqueId];else{const u=(c=t.getVertexBuffer(i))==null?void 0:c.getFloatData(l);o=new WB(this._engine,Float32Array.BYTES_PER_ELEMENT*l*r),o.update(u),a[t.uniqueId]=o}e.setStorageBuffer(n,o)}_prepareStorage(e,t,i,r,n,a){let o;r[i]?o=r[i]:(o=new WB(this._engine,Float32Array.BYTES_PER_ELEMENT*n),r[i]=o),o.update(a),e.setStorageBuffer(t,o)}async processAsync(e){await this.registerMeshListAsync(e),this.processMeshList(),await this.fetchResultsForMeshListAsync()}registerMeshListAsync(e){this._disposeForMeshList(),Array.isArray(e)||(e=[e]);let t=0;for(let i=0;i{const r=()=>{const n=this._uniqueComputeShaders.keys();for(let a=n.next();a.done!==!0;a=n.next())if(!a.value.isReady()){setTimeout(r,10);return}i()};r()})}processMeshList(){if(this._processedMeshes.length===0)return;this._uboIndex=0;const e=8*this._processedMeshes.length,t=new Float32Array(e),i=new WB(this._engine,Float32Array.BYTES_PER_ELEMENT*e);this._resultBuffers.push(i);for(let r=0;r0,h=u?l:o;if(this._extractDataAndLink(h,n,$.PositionKind,3,"positionBuffer",this._positionBuffers),n&&n.useBones&&n.computeBonesUsingShaders&&n.skeleton&&n.skeleton.useTextureToStoreBoneMatrices){this._extractDataAndLink(h,n,$.MatricesIndicesKind,4,"indexBuffer",this._indexBuffers),this._extractDataAndLink(h,n,$.MatricesWeightsKind,4,"weightBuffer",this._weightBuffers);const f=n.skeleton.getTransformMatrixTexture(n);h.setTexture("boneSampler",f,!1),n.numBoneInfluencers>4&&(this._extractDataAndLink(h,n,$.MatricesIndicesExtraKind,4,"indexExtraBuffer",this._indexExtraBuffers),this._extractDataAndLink(h,n,$.MatricesWeightsExtraKind,4,"weightExtraBuffer",this._weightExtraBuffers))}const d=this._getUBO();if(u){const f=c._targetStoreTexture;h.setTexture("morphTargets",f,!1),this._prepareStorage(h,"morphTargetInfluences",n.uniqueId,this._morphTargetInfluenceBuffers,c.numInfluencers,c.influences),this._prepareStorage(h,"morphTargetTextureIndices",n.uniqueId,this._morphTargetTextureIndexBuffers,c.numInfluencers,c._morphTargetTextureIndices),d.updateFloat3("morphTargetTextureInfo",c._textureVertexStride,c._textureWidth,c._textureHeight),d.updateInt("morphTargetCount",c.numInfluencers),d.update()}h.setStorageBuffer("resultBuffer",i),h.setUniformBuffer("settings",d),h.dispatch(Math.ceil(a/256)),this._engine.flushFramebuffer()}}fetchResultsForMeshListAsync(){return new Promise(e=>{const t=[];let i=0;for(let l=0;l{let l=0;for(let c=0;c0&&(n.minimizeInPlace(h.getBoundingInfo().minimum),a.maximizeInPlace(h.getBoundingInfo().maximum)),h._refreshBoundingInfoDirect(o)}l+=8*this._processedMeshes.length}for(const c of this._resultBuffers)c.dispose();this._resultBuffers=[],this._uboIndex=0,e()})})}_disposeCache(e){for(const t in e)e[t].dispose()}_disposeForMeshList(){for(const e of this._resultBuffers)e.dispose();this._resultBuffers=[],this._processedMeshes=[],this._computeShaders=[],this._uniqueComputeShaders=new Set}dispose(){this._disposeCache(this._positionBuffers),this._positionBuffers={},this._disposeCache(this._indexBuffers),this._indexBuffers={},this._disposeCache(this._weightBuffers),this._weightBuffers={},this._disposeCache(this._morphTargetInfluenceBuffers),this._morphTargetInfluenceBuffers={},this._disposeCache(this._morphTargetTextureIndexBuffers),this._morphTargetTextureIndexBuffers={};for(const e of this._ubos)e.dispose();this._ubos=[],this._computeShadersCache={},this._engine=void 0,this._disposeForMeshList()}}const Dvt=Object.freeze(Object.defineProperty({__proto__:null,ComputeShaderBoundingHelper:_ke},Symbol.toStringTag,{value:"Module"}));class Uk{constructor(e,t,i,r,n,a){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=n,this._creationFunc=a,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const t=s.getBoundingInfo();!s.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(s)};r6.CreationFuncForSubMeshes=(s,e)=>{s.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(s)};gt.prototype.createOrUpdateSelectionOctree=function(s=64,e=2){let t=this._getComponent(ot.NAME_OCTREE);t||(t=new Zge(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new r6(r6.CreationFuncForMeshes,s,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(gt.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});Li.prototype.createOrUpdateSubmeshesOctree=function(s=64,e=2){const t=this.getScene();let i=t._getComponent(ot.NAME_OCTREE);i||(i=new Zge(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new r6(r6.CreationFuncForSubMeshes,s,e)),this.computeWorldMatrix(!0);const n=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(n.minimumWorld,n.maximumWorld,this.subMeshes),this._submeshesOctree};class Zge{constructor(e){this.name=ot.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new $i(D.Zero(),new D(1,1,1)),e=e||Rt.LastCreatedScene,e&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=t=>this.getActiveSubMeshCandidates(t),this.scene.getCollidingSubMeshCandidates=(t,i)=>this.getCollidingSubMeshCandidates(t,i),this.scene.getIntersectingSubMeshCandidates=(t,i)=>this.getIntersectingSubMeshCandidates(t,i))}register(){this.scene.onMeshRemovedObservable.add(e=>{const t=this.scene.selectionOctree;if(t!=null){const i=t.dynamicContent.indexOf(e);i!==-1&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{const t=this.scene.selectionOctree;t!=null&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return((e=this.scene._selectionOctree)==null?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?($i.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function QJ(s){const e=s.height||2;let t=s.diameterTop===0?0:s.diameterTop||s.diameter||1,i=s.diameterBottom===0?0:s.diameterBottom||s.diameter||1;t=t||1e-5,i=i||1e-5;const r=(s.tessellation||24)|0,n=(s.subdivisions||1)|0,a=!!s.hasRings,o=!!s.enclose,l=s.cap===0?0:s.cap||Ee.CAP_ALL,c=s.arc&&(s.arc<=0||s.arc>1)?1:s.arc||1,u=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,h=s.faceUV||new Array(3),d=s.faceColors,f=c!==1&&o?2:0,p=a?n:1,m=2+(1+f)*p;let g;for(g=0;g{const ce=ue?t/2:i/2;if(ce===0)return;let N,B,Y;const te=ue?h[m-1]:h[0];let oe=null;d&&(oe=ue?d[m-1]:d[0]);const ne=y.length/3,pe=ue?e/2:-e/2,ye=new D(0,pe,0);y.push(ye.x,ye.y,ye.z),v.push(0,ue?1:-1,0);const Ie=te.y+(te.w-te.y)*.5;x.push(te.x+(te.z-te.x)*.5,Qr?1-Ie:Ie),oe&&A.push(oe.r,oe.g,oe.b,oe.a);const Ne=new we(.5,.5);for(Y=0;Y<=r;Y++){N=Math.PI*2*Y*c/r;const Ve=Math.cos(-N),nt=Math.sin(-N);B=new D(Ve*ce,pe,nt*ce);const Ke=new we(Ve*Ne.x+.5,nt*Ne.y+.5);y.push(B.x,B.y,B.z),v.push(0,ue?1:-1,0);const Et=te.y+(te.w-te.y)*Ke.y;x.push(te.x+(te.z-te.x)*Ke.x,Qr?1-Et:Et),oe&&A.push(oe.r,oe.g,oe.b,oe.a)}for(Y=0;Y((a===void 0||!(a instanceof gt))&&(a!==void 0&&(l=o||Ee.DEFAULTSIDE,o=a),a=n,n=1),ou(s,{height:e,diameterTop:t,diameterBottom:i,tessellation:r,subdivisions:n,sideOrientation:l,updatable:o},a));ns.AddNodeConstructor("Light_Type_3",(s,e)=>()=>new $f(s,D.Zero(),e));class $f extends Zi{constructor(e,t,i){super(e,i),this.groundColor=new Re(0,0,0),this.direction=t||D.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=D.Normalize(e.subtract(D.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=D.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=D.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=he.Identity()),this._worldMatrix}getTypeID(){return Zi.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}F([br()],$f.prototype,"groundColor",void 0);F([Pn()],$f.prototype,"direction",void 0);ve("BABYLON.HemisphericLight",$f);class is{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?t=this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:t=this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new $f("shared gizmo light",new D(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Re.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return is._DefaultUtilityLayer==null?is._CreateDefaultUtilityLayerFromScene(Rt.LastCreatedScene):is._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return is._DefaultUtilityLayer=new is(e),is._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{is._DefaultUtilityLayer=null}),is._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return is._DefaultKeepDepthUtilityLayer==null&&(is._DefaultKeepDepthUtilityLayer=new is(Rt.LastCreatedScene),is._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,is._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{is._DefaultKeepDepthUtilityLayer=null})),is._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new Ae,this.utilityLayerScene=new gt(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(i=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&i.type!==yt.POINTERMOVE&&i.type!==yt.POINTERUP&&i.type!==yt.POINTERDOWN&&i.type!==yt.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const r=i.event;if(e.isPointerCaptured(r.pointerId)){this._pointerCaptures[r.pointerId]=!1;return}const n=o=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==o?l=i.nearInteractionPickingInfo:l=new Ko;else if(o!==this.utilityLayerScene&&i.originalPickingInfo)l=i.originalPickingInfo;else{let c=null;this._renderCamera&&(c=o._activeCamera,o._activeCamera=this._renderCamera,i.ray=null),l=i.ray?o.pickWithRay(i.ray):o.pick(e.pointerX,e.pointerY),c&&(o._activeCamera=c)}return l},a=n(this.utilityLayerScene);if(!i.ray&&a&&(i.ray=a.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(i),this.onlyCheckPointerDownEvents&&i.type!=yt.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Df(i.type,i.event,a),i.type),i.type===yt.POINTERUP&&this._pointerCaptures[r.pointerId]&&(this._pointerCaptures[r.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)a&&a.hit&&(i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Df(i.type,i.event,a),i.type),i.skipOnPointerObservable=!0);else{const o=n(e),l=i.event;o&&a&&(a.distance===0&&o.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):i.type===yt.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===yt.POINTERMOVE||i.type===yt.POINTERUP)&&(this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,o,l)):!this._pointerCaptures[l.pointerId]&&(a.distance0)):!this._pointerCaptures[l.pointerId]&&a.distance>=o.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):((i.type===yt.POINTERMOVE||i.type===yt.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,a,l))),i.type===yt.POINTERUP&&this._pointerCaptures[l.pointerId]&&(this._pointerCaptures[l.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(i=>{this.shouldRender&&i==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new Df(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}is._DefaultUtilityLayer=null;is._DefaultKeepDepthUtilityLayer=null;var Hue;(function(s){s[s.Origin=0]="Origin",s[s.Pivot=1]="Pivot"})(Hue||(Hue={}));var jue;(function(s){s[s.World=0]="World",s[s.Local=1]="Local"})(jue||(jue={}));class jn{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(t=>{t.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==1;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=is.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=0,this._updateScale=!0,this._coordinatesMode=1,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=he.RotationY(Math.PI),this._rootMesh=new Ee("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=Pe.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{this._update()})}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==1&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new D(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const i=e._isMesh||e.getClassName()==="AbstractMesh"||e.getClassName()==="TransformNode"||e.getClassName()==="InstancedMesh"?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,jn.PreserveScaling?i:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,se.Vector3[0]);let r=this.scaleRatio;if(t.mode==Nt.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){const n=t.orthoTop-t.orthoBottom;r*=n}}else{const n=t.getScene().useRightHandedSystem?D.RightHandedForwardReadOnly:D.LeftHandedForwardReadOnly,a=t.getDirection(n);r*=D.Dot(se.Vector3[0],a)}this._rootMesh.scaling.setAll(r),e._getWorldMatrixDeterminant()<0&&!jn.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),se.Matrix[0]),se.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix()){e.getPivotMatrix().invertToRef(se.Matrix[5]),se.Matrix[5].multiplyToRef(t,i);return}i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const n=se.Matrix[1];e.parent._worldMatrix.invertToRef(n),this._attachedNode._worldMatrix.multiplyToRef(n,se.Matrix[0]),t=se.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,se.Matrix[1]),i=se.Matrix[1]):i=t,i.decompose(se.Vector3[1],se.Quaternion[0],se.Vector3[0]),this._attachedNode.getClassName()==="FreeCamera"||this._attachedNode.getClassName()==="FlyCamera"||this._attachedNode.getClassName()==="ArcFollowCamera"||this._attachedNode.getClassName()==="TargetCamera"||this._attachedNode.getClassName()==="TouchCamera"||this._attachedNode.getClassName()==="UniversalCamera"){const n=this._attachedNode;n.rotation=se.Quaternion[0].toEulerAngles(),n.rotationQuaternion&&(n.rotationQuaternion.copyFrom(se.Quaternion[0]),n.rotationQuaternion.normalize())}e.position.copyFrom(se.Vector3[0])}else if(this._attachedNode._isMesh||this._attachedNode.getClassName()==="AbstractMesh"||this._attachedNode.getClassName()==="TransformNode"||this._attachedNode.getClassName()==="InstancedMesh"){const e=this._attachedNode;if(e.parent){const t=se.Matrix[0],i=se.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const r=se.Matrix[4];if(this._handlePivotMatrixInverse(e,i,r),r.decompose(se.Vector3[0],se.Quaternion[0],e.position,jn.PreserveScaling?e:void 0,jn.UseAbsoluteScaling),se.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const n=se.Quaternion[1];Pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,n);const a=se.Matrix[2];he.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,a);const o=se.Matrix[2];n.toRotationMatrix(o);const l=e.getPivotMatrix(),c=se.Matrix[3];l.invertToRef(c),l.multiplyToRef(a,se.Matrix[4]),se.Matrix[4].multiplyToRef(o,se.Matrix[5]),se.Matrix[5].multiplyToRef(c,se.Matrix[6]),se.Matrix[6].getTranslationToRef(se.Vector3[1]),e.position.subtractInPlace(se.Vector3[1])}}else{const t=se.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(se.Vector3[0],se.Quaternion[0],e.position,jn.PreserveScaling?e:void 0,jn.UseAbsoluteScaling)}se.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(se.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(se.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=se.Quaternion[0].toEulerAngles())}else if(this._attachedNode.getClassName()==="Bone"){const e=this._attachedNode,t=e.getParent();if(t){const i=se.Matrix[0],r=se.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r),e.getLocalMatrix().copyFrom(r)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===Zi.LIGHTTYPEID_DIRECTIONALLIGHT||t===Zi.LIGHTTYPEID_SPOTLIGHT||t===Zi.LIGHTTYPEID_POINTLIGHT){const i=e.parent;if(i){const r=se.Matrix[0],n=se.Matrix[1];i.getWorldMatrix().invertToRef(r),e.getWorldMatrix().multiplyToRef(r,n),n.decompose(void 0,se.Quaternion[0],se.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,se.Quaternion[0],se.Vector3[0]);e.position=new D(se.Vector3[0].x,se.Vector3[0].y,se.Vector3[0].z),e.direction&&(e.direction=new D(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach(i=>{i.material=t,i.color&&(i.color=t.diffuseColor)})}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add(n=>{var a,o;if(n.pickInfo){if(n.type===yt.POINTERMOVE){if(i)return;t.forEach(l=>{var c,u;if(l.colliderMeshes&&l.gizmoMeshes){const h=((u=l.colliderMeshes)==null?void 0:u.indexOf((c=n==null?void 0:n.pickInfo)==null?void 0:c.pickedMesh))!=-1,d=l.dragBehavior.enabled?h||l.active?l.hoverMaterial:l.material:l.disableMaterial;l.gizmoMeshes.forEach(f=>{f.material=d,f.color&&(f.color=d.diffuseColor)})}})}if(n.type===yt.POINTERDOWN&&t.has((a=n.pickInfo.pickedMesh)==null?void 0:a.parent)){i=!0;const l=t.get((o=n.pickInfo.pickedMesh)==null?void 0:o.parent);l.active=!0,t.forEach(c=>{var d,f;const h=(((f=c.colliderMeshes)==null?void 0:f.indexOf((d=n==null?void 0:n.pickInfo)==null?void 0:d.pickedMesh))!=-1||c.active)&&c.dragBehavior.enabled?c.hoverMaterial:c.disableMaterial;c.gizmoMeshes.forEach(p=>{p.material=h,p.color&&(p.color=h.diffuseColor)})})}n.type===yt.POINTERUP&&t.forEach(l=>{l.active=!1,i=!1,l.gizmoMeshes.forEach(c=>{c.material=l.dragBehavior.enabled?l.material:l.disableMaterial,c.color&&(c.color=l.material.diffuseColor)})})}})}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}jn.PreserveScaling=!1;jn.UseAbsoluteScaling=!0;class Bf extends jn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,r=!1){const n=new _t("arrow",e),a=ou("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=ou("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return a.parent=n,a.material=t,a.rotation.x=Math.PI/2,a.position.z+=.3,o.parent=n,o.material=t,o.position.z+=.275/2,o.rotation.x=Math.PI/2,r&&(o.visibility=0,a.visibility=0),n}static _CreateArrowInstance(e,t){const i=new _t("arrow",e);for(const r of t.getChildMeshes()){const n=r.createInstance(r.name);n.parent=i}return i}constructor(e,t=Re.Gray(),i=is.DefaultUtilityLayer,r=null,n=1,a=Re.Yellow(),o=Re.Gray()){var p;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new et("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Re(.1,.1,.1)),this._hoverMaterial=new et("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._disableMaterial=new et("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const l=Bf._CreateArrow(i.utilityLayerScene,this._coloredMaterial,n),c=Bf._CreateArrow(i.utilityLayerScene,this._coloredMaterial,n+4,!0);this._gizmoMesh=new Ee("",i.utilityLayerScene),this._gizmoMesh.addChild(l),this._gizmoMesh.addChild(c),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let u=0;const h={snapDistance:0};this.dragBehavior=new sl({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(m=>{if(this.attachedNode){let g=!1;if(this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(se.Vector3[2]),se.Vector3[2].addInPlace(m.delta),this.dragBehavior.validateDrag(se.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(m.delta.x,m.delta.y,m.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(m.delta.x,m.delta.y,m.delta.z),this.attachedNode.updateCache(),g=!0);else if(u+=m.dragDistance,Math.abs(u)>this.snapDistance){const _=Math.floor(Math.abs(u)/this.snapDistance);u=u%this.snapDistance,m.delta.normalizeToRef(se.Vector3[1]),se.Vector3[1].scaleInPlace(this.snapDistance*_),this.attachedNode.getWorldMatrix().getTranslationToRef(se.Vector3[2]),se.Vector3[2].addInPlace(se.Vector3[1]),this.dragBehavior.validateDrag(se.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(se.Vector3[1].x,se.Vector3[1].y,se.Vector3[1].z),this.attachedNode.updateCache(),h.snapDistance=this.snapDistance*_*Math.sign(u),this.onSnapObservable.notifyObservers(h),g=!0)}g&&this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{this._dragging=!0}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1});const d=i._getSharedGizmoLight();d.includedOnlyMeshes=d.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const f={gizmoMeshes:l.getChildMeshes(),colliderMeshes:c.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(p=this._parent)==null||p.addToAxisCache(c,f),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(m=>{var g;if(!this._customMeshSet&&(this._isHovered=f.colliderMeshes.indexOf((g=m==null?void 0:m.pickInfo)==null?void 0:g.pickedMesh)!=-1,!this._parent)){const _=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(f.gizmoMeshes,_)}}),this.dragBehavior.onEnabledObservable.add(m=>{this._setGizmoMeshMaterial(f.gizmoMeshes,m?f.material:f.disableMaterial)})}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}class hv{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,r,n,a,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||Rt.LastCreatedScene,!!e){if(!r){const l=new et("xAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Re.Red().scale(.5),r=Bf._CreateArrow(e,l,o)}if(!n){const l=new et("yAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Re.Green().scale(.5),n=Bf._CreateArrow(e,l,o)}if(!a){const l=new et("zAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Re.Blue().scale(.5),a=Bf._CreateArrow(e,l,o)}this._xAxis=r,this._yAxis=n,this._zAxis=a,this.scaleLines=t,i!=null&&(hv._SetRenderingGroupId(this._xAxis,i),hv._SetRenderingGroupId(this._yAxis,i),hv._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new D,D.Right(),D.Up(),D.Forward())}}update(e,t,i,r){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(r)}createInstance(){const e=Bf._CreateArrowInstance(this.scene,this._xAxis),t=Bf._CreateArrowInstance(this.scene,this._yAxis),i=Bf._CreateArrowInstance(this.scene,this._zAxis),r=new hv(this.scene,this.scaleLines,null,e,t,i);return r._instanced=!0,r}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach(i=>{i.renderingGroupId=t})}}class Ovt extends hv{constructor(e,t,i,r=1){super(e,r),this.pos=D.Zero(),this.xaxis=D.Zero(),this.yaxis=D.Zero(),this.zaxis=D.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(Da.X,this.mesh,this.xaxis),e.getDirectionToRef(Da.Y,this.mesh,this.yaxis),e.getDirectionToRef(Da.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(gt.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new s6(this)),this._debugLayer},enumerable:!0,configurable:!0});var Xue;(function(s){s[s.Properties=0]="Properties",s[s.Debug=1]="Debug",s[s.Statistics=2]="Statistics",s[s.Tools=3]="Tools",s[s.Settings=4]="Settings"})(Xue||(Xue={}));class s6{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new Ae),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new Ae),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||Rt.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const i of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(i);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const i of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(i);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...s6.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&(Object.prototype.toString.call(t)=="[object String]"?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){if(typeof INSPECTOR<"u")return INSPECTOR;if(typeof BABYLON<"u"&&typeof BABYLON.Inspector<"u")return BABYLON}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}popupSceneExplorer(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupSceneExplorer()}popupInspector(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupInspector()}popupEmbed(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupEmbed()}show(e){return new Promise(t=>{if(typeof this.BJSINSPECTOR>"u"){const i=e&&e.inspectorURL?e.inspectorURL:s6.InspectorURL;Me.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}s6.InspectorURL=`${Me._DefaultCdnUrl}/v${Ge.Version}/inspector/babylon.inspector.bundle.js`;s6.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function $J(s){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[];let n=[];const a=s.width||s.size||1,o=s.height||s.size||1,l=s.depth||s.size||1,c=s.wrap||!1;let u=s.topBaseAt===void 0?1:s.topBaseAt,h=s.bottomBaseAt===void 0?0:s.bottomBaseAt;u=(u+4)%4,h=(h+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let p=d[u],m=f[h],g=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(c){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],g=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let C=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],T=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const w=[17,18,19,16],P=[22,23,20,21];for(;p>0;)C.unshift(C.pop()),w.unshift(w.pop()),p--;for(;m>0;)T.unshift(T.pop()),P.unshift(P.pop()),m--;C=C.flat(),T=T.flat(),g=g.concat(C).concat(T),t.push(w[0],w[2],w[3],w[0],w[1],w[2]),t.push(P[0],P[2],P[3],P[0],P[1],P[2])}const _=[a/2,o/2,l/2];n=g.reduce((C,T,w)=>C.concat(T*_[w%3]),[]);const y=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,v=s.faceUV||new Array(6),x=s.faceColors,A=[];for(let C=0;C<6;C++)v[C]===void 0&&(v[C]=new mt(0,0,1,1)),x&&x[C]===void 0&&(x[C]=new Ze(1,1,1,1));for(let C=0;C<6;C++)if(r.push(v[C].z,Qr?1-v[C].w:v[C].w),r.push(v[C].x,Qr?1-v[C].w:v[C].w),r.push(v[C].x,Qr?1-v[C].y:v[C].y),r.push(v[C].z,Qr?1-v[C].y:v[C].y),x)for(let T=0;T<4;T++)A.push(x[C].r,x[C].g,x[C].b,x[C].a);at._ComputeSides(y,n,t,i,r,s.frontUVs,s.backUVs);const b=new at;if(b.indices=t,b.positions=n,b.normals=i,b.uvs=r,x){const C=y===at.DOUBLESIDE?A.concat(A):A;b.colors=C}return b}function vke(s){const e=s.width||s.size||1,t=s.height||s.size||1,i=s.depth||s.size||1,r=(s.widthSegments||s.segments||1)|0,n=(s.heightSegments||s.segments||1)|0,a=(s.depthSegments||s.segments||1)|0,o=new he,l=new he,c=new he,u=P1({width:e,height:i,subdivisionsX:r,subdivisionsY:a});he.TranslationToRef(0,-t/2,0,l),he.RotationZToRef(Math.PI,o),o.multiplyToRef(l,c),u.transform(c);const h=P1({width:e,height:i,subdivisionsX:r,subdivisionsY:a});he.TranslationToRef(0,t/2,0,c),h.transform(c);const d=P1({width:t,height:i,subdivisionsX:n,subdivisionsY:a});he.TranslationToRef(-e/2,0,0,l),he.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,c),d.transform(c);const f=P1({width:t,height:i,subdivisionsX:n,subdivisionsY:a});he.TranslationToRef(e/2,0,0,l),he.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,c),f.transform(c);const p=P1({width:e,height:t,subdivisionsX:r,subdivisionsY:n});he.TranslationToRef(0,0,-i/2,l),he.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,c),p.transform(c);const m=P1({width:e,height:t,subdivisionsX:r,subdivisionsY:n});return he.TranslationToRef(0,0,i/2,l),he.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,c),m.transform(c),u.merge([h,f,d,p,m],!0),u}function ph(s,e={},t=null){const i=new Ee(s,t);return e.sideOrientation=Ee._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,$J(e).applyToMesh(i,e.updatable),i}const Nvt={CreateBox:ph};at.CreateBox=$J;Ee.CreateBox=(s,e,t=null,i,r)=>ph(s,{size:e,sideOrientation:r,updatable:i},t);function ZJ(s){const e=(s.segments||32)|0,t=s.diameterX||s.diameter||1,i=s.diameterY||s.diameter||1,r=s.diameterZ||s.diameter||1,n=s.arc&&(s.arc<=0||s.arc>1)?1:s.arc||1,a=s.slice&&s.slice<=0?1:s.slice||1,o=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,l=!!s.dedupTopBottomIndices,c=new D(t/2,i/2,r/2),u=2+e,h=2*u,d=[],f=[],p=[],m=[];for(let _=0;_<=u;_++){const y=_/u,v=y*Math.PI*a;for(let x=0;x<=h;x++){const A=x/h,b=A*Math.PI*2*n,C=he.RotationZ(-v),T=he.RotationY(b),w=D.TransformCoordinates(D.Up(),C),P=D.TransformCoordinates(w,T),M=P.multiply(c),R=P.divide(c).normalize();f.push(M.x,M.y,M.z),p.push(R.x,R.y,R.z),m.push(A,Qr?1-y:y)}if(_>0){const x=f.length/3;for(let A=x-2*(h+1);A+h+21&&(d.push(A),d.push(A+1),d.push(A+h+1)),(_kc(s,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:n,updatable:r},i);class ks{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}ks.DistanceJoint=0;ks.HingeJoint=1;ks.BallAndSocketJoint=2;ks.WheelJoint=3;ks.SliderJoint=4;ks.PrismaticJoint=5;ks.UniversalJoint=6;ks.Hinge2Joint=ks.WheelJoint;ks.PointToPointJoint=8;ks.SpringJoint=9;ks.LockJoint=10;class Bvt extends ks{constructor(e){super(ks.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class qge extends ks{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class kvt extends qge{constructor(e){super(ks.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class Uvt extends qge{constructor(e){super(ks.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}Ee._PhysicsImpostorParser=function(s,e,t){return new oi(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},s)};class oi{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=D.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new Pe,this._tmpQuat2=new Pe,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new Pe),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(n=>{n(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(n=>{n(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,oi._TmpVecs[0]),this.object.translate(oi._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=n=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;const a=this._physicsEngine.getImpostorWithPhysicsBody(n.body);a&&(this.onCollideEvent&&this.onCollideEvent(this,a),this._onPhysicsCollideCallbacks.filter(o=>o.otherImpostors.indexOf(a)!==-1).forEach(o=>{o.callback(this,a,n.point,n.distance,n.impulse,n.normal)}))},!this.object){fe.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&fe.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=Pe.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new Pe),this._options.mass=i.mass===void 0?0:i.mass,this._options.friction=i.friction===void 0?.2:i.friction,this._options.restitution=i.restitution===void 0?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=i.pressure===void 0?200:i.pressure,this._options.stiffness=i.stiffness===void 0?1:i.stiffness,this._options.velocityIterations=i.velocityIterations===void 0?20:i.velocityIterations,this._options.positionIterations=i.positionIterations===void 0?20:i.positionIterations,this._options.fixedPoints=i.fixedPoints===void 0?0:i.fixedPoints,this._options.margin=i.margin===void 0?0:i.margin,this._options.damping=i.damping===void 0?0:i.damping,this._options.path=i.path===void 0?null:i.path,this._options.shape=i.shape===void 0?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&fe.Warn("You must affect impostors to children before affecting impostor to parent.")):fe.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),!this._isDisposed&&(!this.parent||this._options.ignoreParent)&&this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof Li?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=oi.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const n=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return n.x=Math.abs(n.x),n.y=Math.abs(n.y),n.z=Math.abs(n.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),n}else return oi.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):D.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):D.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):fe.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):fe.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let r=-1;this._onPhysicsCollideCallbacks.some((a,o)=>{if(a.callback===t&&a.otherImpostors.length===i.length){const l=a.otherImpostors.every(c=>i.indexOf(c)>-1);return l&&(r=o),l}return!1})?this._onPhysicsCollideCallbacks.splice(r,1):fe.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):Pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const r=new ks(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,n){if(!this._physicsEngine)return this;const a=this._physicsEngine.getPhysicsPlugin();return a.appendAnchor?(this._physicsEngine&&a.appendAnchor(this,e,t,i,r,n),this):this}addHook(e,t,i,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendHook(this,e,t,i,r),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new oi(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new Pe),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,n){const a=oi._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(n){const l=oi._TmpQuat;o.rotationQuaternion.multiplyToRef(n,l),e.setRotationQuaternion(l,1,t)}else e.setRotationQuaternion(o.rotationQuaternion,1,t);a.x=0,a.y=0,a.z=0,i&&(a.x=i.x,a.y=i.y,a.z=i.z,e.getDirectionToRef(a,t,a),r==null&&(r=i.length()),a.x*=r,a.y*=r,a.z*=r),e.getParent()?(a.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(a,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=a.x,t.position.y-=a.y,t.position.z-=a.z)}syncImpostorWithBone(e,t,i,r,n,a){const o=this.object;if(o.rotationQuaternion)if(n){const u=oi._TmpQuat;e.getRotationQuaternionToRef(1,t,u),u.multiplyToRef(n,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const l=oi._TmpVecs[0],c=oi._TmpVecs[1];a||(a=oi._TmpVecs[2],a.x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,c),e.getAbsolutePositionToRef(t,l),r==null&&i&&(r=i.length()),r!=null&&(l.x+=c.x*r,l.y+=c.y*r,l.z+=c.z*r),o.setAbsolutePosition(l)}}oi.DEFAULT_OBJECT_SIZE=new D(1,1,1);oi.IDENTITY_QUATERNION=Pe.Identity();oi._TmpVecs=vh(3,D.Zero);oi._TmpQuat=Pe.Identity();oi.NoImpostor=0;oi.SphereImpostor=1;oi.BoxImpostor=2;oi.PlaneImpostor=3;oi.MeshImpostor=4;oi.CapsuleImpostor=6;oi.CylinderImpostor=7;oi.ParticleImpostor=8;oi.HeightmapImpostor=9;oi.ConvexHullImpostor=10;oi.CustomImpostor=100;oi.RopeImpostor=101;oi.ClothImpostor=102;oi.SoftbodyImpostor=103;function qJ(s={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(s.subdivisions?s.subdivisions:2,1)|0,t=Math.max(s.tessellation?s.tessellation:16,3)|0,i=Math.max(s.height?s.height:1,0),r=Math.max(s.radius?s.radius:.25,0),n=Math.max(s.capSubdivisions?s.capSubdivisions:6,1)|0,a=t,o=e,l=Math.max(s.radiusTop?s.radiusTop:r,0),c=Math.max(s.radiusBottom?s.radiusBottom:r,0),u=i-(l+c),h=0,d=2*Math.PI,f=Math.max(s.topCapSubdivisions?s.topCapSubdivisions:n,1),p=Math.max(s.bottomCapSubdivisions?s.bottomCapSubdivisions:n,1),m=Math.acos((c-l)/i);let g=[];const _=[],y=[],v=[];let x=0;const A=[],b=u*.5,C=Math.PI*.5;let T,w;const P=D.Zero(),M=D.Zero(),R=Math.cos(m),I=Math.sin(m),L=new we(l*I,b+l*R).subtract(new we(c*I,-b+c*R)).length(),k=l*m+L+c*(C-m);let V=0;for(w=0;w<=f;w++){const K=[],U=C-m*(w/f);V+=l*m/f;const W=Math.cos(U),Z=Math.sin(U),q=W*l;for(T=0;T<=a;T++){const ie=T/a,ae=ie*d+h,ue=Math.sin(ae),ce=Math.cos(ae);M.x=q*ue,M.y=b+Z*l,M.z=q*ce,_.push(M.x,M.y,M.z),P.set(W*ue,Z,W*ce),y.push(P.x,P.y,P.z),v.push(ie,Qr?V/k:1-V/k),K.push(x),x++}A.push(K)}const H=i-l-c+R*l-R*c,j=I*(c-l)/H;for(w=1;w<=o;w++){const K=[];V+=L/o;const U=I*(w*(c-l)/o+l);for(T=0;T<=a;T++){const W=T/a,Z=W*d+h,q=Math.sin(Z),ie=Math.cos(Z);M.x=U*q,M.y=b+R*l-w*H/o,M.z=U*ie,_.push(M.x,M.y,M.z),P.set(q,j,ie).normalize(),y.push(P.x,P.y,P.z),v.push(W,Qr?V/k:1-V/k),K.push(x),x++}A.push(K)}for(w=1;w<=p;w++){const K=[],U=C-m-(Math.PI-m)*(w/p);V+=c*m/p;const W=Math.cos(U),Z=Math.sin(U),q=W*c;for(T=0;T<=a;T++){const ie=T/a,ae=ie*d+h,ue=Math.sin(ae),ce=Math.cos(ae);M.x=q*ue,M.y=-b+Z*c,M.z=q*ce,_.push(M.x,M.y,M.z),P.set(W*ue,Z,W*ce),y.push(P.x,P.y,P.z),v.push(ie,Qr?V/k:1-V/k),K.push(x),x++}A.push(K)}for(T=0;TOz(s,e,t);at.CreateCapsule=qJ;function Jge(s){let e=s.pathArray;const t=s.closeArray||!1,i=s.closePath||!1,r=s.invertUV||!1,n=Math.floor(e[0].length/2);let a=s.offset||n;a=a>n?n:Math.floor(a);const o=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,l=s.uvs,c=s.colors,u=[],h=[],d=[],f=[],p=[],m=[],g=[],_=[];let y;const v=[],x=[];let A,b,C;if(e.length<2){const te=[],oe=[];for(b=0;b0&&(I=M[C].subtract(M[C-1]).length(),L=I+g[A],p[A].push(L),g[A]=L),C++;i&&(C--,u.push(M[0].x,M[0].y,M[0].z),I=M[C].subtract(M[0]).length(),L=I+g[A],p[A].push(L),g[A]=L),v[A]=R+w,x[A]=T,T+=R+w}let k,V,H=null,j=null;for(b=0;b{let p=i[0].length;const m=o;let g=0;const _=m._originalBuilderSideOrientation===Ee.DOUBLESIDE?2:1;for(let y=1;y<=_;++y)for(let v=0;vc_(s,{pathArray:e,closeArray:t,closePath:i,offset:r,updatable:a,sideOrientation:o,instance:l},n);function JJ(s){const e=[],t=[],i=[],r=[],n=s.radius||.5,a=s.tessellation||64,o=s.arc&&(s.arc<=0||s.arc>1)?1:s.arc||1,l=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE;e.push(0,0,0),r.push(.5,.5);const c=Math.PI*2*o,u=o===1?c/a:c/(a-1);let h=0;for(let p=0;piD(s,{radius:e,tessellation:t,sideOrientation:n,updatable:r},i);function aP(s){const e=s.pattern||Ee.NO_FLIP,t=s.tileWidth||s.tileSize||1,i=s.tileHeight||s.tileSize||1,r=s.alignHorizontal||0,n=s.alignVertical||0,a=s.width||s.size||1,o=Math.floor(a/t);let l=a-o*t;const c=s.height||s.size||1,u=Math.floor(c/i);let h=c-u*i;const d=t*o/2,f=i*u/2;let p=0,m=0,g=0,_=0,y=0,v=0;if(l>0||h>0){switch(g=-d,_=-f,y=d,v=f,r){case Ee.CENTER:l/=2,g-=l,y+=l;break;case Ee.LEFT:y+=l,p=-l/2;break;case Ee.RIGHT:g-=l,p=l/2;break}switch(n){case Ee.CENTER:h/=2,_-=h,v+=h;break;case Ee.BOTTOM:v+=h,m=-h/2;break;case Ee.TOP:_-=h,m=h/2;break}}const x=[],A=[],b=[];b[0]=[0,0,1,0,1,1,0,1],b[1]=[0,0,1,0,1,1,0,1],(e===Ee.ROTATE_TILE||e===Ee.ROTATE_ROW)&&(b[1]=[1,1,0,1,0,0,1,0]),(e===Ee.FLIP_TILE||e===Ee.FLIP_ROW)&&(b[1]=[1,0,0,0,0,1,1,1]),(e===Ee.FLIP_N_ROTATE_TILE||e===Ee.FLIP_N_ROTATE_ROW)&&(b[1]=[0,1,1,1,1,0,0,0]);let C=[];const T=[],w=[];let P=0;for(let L=0;L0||h>0){const L=h>0&&(n===Ee.CENTER||n===Ee.TOP),k=h>0&&(n===Ee.CENTER||n===Ee.BOTTOM),V=l>0&&(r===Ee.CENTER||r===Ee.RIGHT),H=l>0&&(r===Ee.CENTER||r===Ee.LEFT);let j=[],z,K,U,W;if(L&&V&&(x.push(g+p,_+m,0),x.push(-d+p,_+m,0),x.push(-d+p,_+h+m,0),x.push(g+p,_+h+m,0),w.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,z=1-l/t,K=1-h/i,U=1,W=1,j=[z,K,U,K,U,W,z,W],e===Ee.ROTATE_ROW&&(j=[1-z,1-K,1-U,1-K,1-U,1-W,1-z,1-W]),e===Ee.FLIP_ROW&&(j=[1-z,K,1-U,K,1-U,W,1-z,W]),e===Ee.FLIP_N_ROTATE_ROW&&(j=[z,1-K,U,1-K,U,1-W,z,1-W]),C=C.concat(j),T.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&H&&(x.push(d+p,_+m,0),x.push(y+p,_+m,0),x.push(y+p,_+h+m,0),x.push(d+p,_+h+m,0),w.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,z=0,K=1-h/i,U=l/t,W=1,j=[z,K,U,K,U,W,z,W],(e===Ee.ROTATE_ROW||e===Ee.ROTATE_TILE&&o%2===0)&&(j=[1-z,1-K,1-U,1-K,1-U,1-W,1-z,1-W]),(e===Ee.FLIP_ROW||e===Ee.FLIP_TILE&&o%2===0)&&(j=[1-z,K,1-U,K,1-U,W,1-z,W]),(e===Ee.FLIP_N_ROTATE_ROW||e===Ee.FLIP_N_ROTATE_TILE&&o%2===0)&&(j=[z,1-K,U,1-K,U,1-W,z,1-W]),C=C.concat(j),T.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),k&&V&&(x.push(g+p,f+m,0),x.push(-d+p,f+m,0),x.push(-d+p,v+m,0),x.push(g+p,v+m,0),w.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,z=1-l/t,K=0,U=1,W=h/i,j=[z,K,U,K,U,W,z,W],(e===Ee.ROTATE_ROW&&u%2===1||e===Ee.ROTATE_TILE&&u%1===0)&&(j=[1-z,1-K,1-U,1-K,1-U,1-W,1-z,1-W]),(e===Ee.FLIP_ROW&&u%2===1||e===Ee.FLIP_TILE&&u%2===0)&&(j=[1-z,K,1-U,K,1-U,W,1-z,W]),(e===Ee.FLIP_N_ROTATE_ROW&&u%2===1||e===Ee.FLIP_N_ROTATE_TILE&&u%2===0)&&(j=[z,1-K,U,1-K,U,1-W,z,1-W]),C=C.concat(j),T.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),k&&H&&(x.push(d+p,f+m,0),x.push(y+p,f+m,0),x.push(y+p,v+m,0),x.push(d+p,v+m,0),w.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,z=0,K=0,U=l/t,W=h/i,j=[z,K,U,K,U,W,z,W],(e===Ee.ROTATE_ROW&&u%2===1||e===Ee.ROTATE_TILE&&(u+o)%2===1)&&(j=[1-z,1-K,1-U,1-K,1-U,1-W,1-z,1-W]),(e===Ee.FLIP_ROW&&u%2===1||e===Ee.FLIP_TILE&&(u+o)%2===1)&&(j=[1-z,K,1-U,K,1-U,W,1-z,W]),(e===Ee.FLIP_N_ROTATE_ROW&&u%2===1||e===Ee.FLIP_N_ROTATE_TILE&&(u+o)%2===1)&&(j=[z,1-K,U,1-K,U,1-W,z,1-W]),C=C.concat(j),T.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L){const Z=[];z=0,K=1-h/i,U=1,W=1,Z[0]=[z,K,U,K,U,W,z,W],Z[1]=[z,K,U,K,U,W,z,W],(e===Ee.ROTATE_TILE||e===Ee.ROTATE_ROW)&&(Z[1]=[1-z,1-K,1-U,1-K,1-U,1-W,1-z,1-W]),(e===Ee.FLIP_TILE||e===Ee.FLIP_ROW)&&(Z[1]=[1-z,K,1-U,K,1-U,W,1-z,W]),(e===Ee.FLIP_N_ROTATE_TILE||e===Ee.FLIP_N_ROTATE_ROW)&&(Z[1]=[z,1-K,U,1-K,U,1-W,z,1-W]);for(let q=0;qZ+M)),M+=C[U].length,i)for(let Z=0;Z<4;Z++)b.push(i[U].r,i[U].g,i[U].b,i[U].a)}const R=new D(0,0,m),I=he.RotationY(Math.PI);y=C[0].map(U=>D.TransformNormal(U,I).add(R)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[]),v=T[0].map(U=>D.TransformNormal(U,I)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[]),y=y.concat(C[1].map(U=>U.subtract(R)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[])),v=v.concat(T[1].map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[]));const L=new D(f,0,0),k=he.RotationY(-Math.PI/2);y=y.concat(C[2].map(U=>D.TransformNormal(U,k).add(L)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[])),v=v.concat(T[2].map(U=>D.TransformNormal(U,k)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[]));const V=he.RotationY(Math.PI/2);y=y.concat(C[3].map(U=>D.TransformNormal(U,V).subtract(L)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[])),v=v.concat(T[3].map(U=>D.TransformNormal(U,V)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[]));const H=new D(0,p,0),j=he.RotationX(Math.PI/2);y=y.concat(C[4].map(U=>D.TransformNormal(U,j).add(H)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[])),v=v.concat(T[4].map(U=>D.TransformNormal(U,j)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[]));const z=he.RotationX(-Math.PI/2);y=y.concat(C[5].map(U=>D.TransformNormal(U,z).subtract(H)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[])),v=v.concat(T[5].map(U=>D.TransformNormal(U,z)).map(U=>[U.x,U.y,U.z]).reduce((U,W)=>U.concat(W),[])),at._ComputeSides(d,y,A,v,x);const K=new at;if(K.indices=A,K.positions=y,K.normals=v,K.uvs=x,i){const U=d===at.DOUBLESIDE?b.concat(b):b;K.colors=U}return K}function i1e(s,e,t=null){const i=new Ee(s,t);return e.sideOrientation=Ee._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,t1e(e).applyToMesh(i,e.updatable),i}const Kvt={CreateTiledBox:i1e};at.CreateTiledBox=t1e;function r1e(s){const e=[],t=[],i=[],r=[],n=s.radius||2,a=s.tube||.5,o=s.radialSegments||32,l=s.tubularSegments||32,c=s.p||2,u=s.q||3,h=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,d=g=>{const _=Math.cos(g),y=Math.sin(g),v=u/c*g,x=Math.cos(v),A=n*(2+x)*.5*_,b=n*(2+x)*y*.5,C=n*Math.sin(v)*.5;return new D(A,b,C)};let f,p;for(f=0;f<=o;f++){const _=f%o/o*2*c*Math.PI,y=d(_),v=d(_+.01),x=v.subtract(y);let A=v.add(y);const b=D.Cross(x,A);for(A=D.Cross(b,x),b.normalize(),A.normalize(),p=0;peee(s,{radius:e,tube:t,radialSegments:i,tubularSegments:r,p:n,q:a,sideOrientation:c,updatable:l},o);Ee._LinesMeshParser=(s,e)=>Jm.Parse(s,e);class Jm extends Ee{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,r=null,n,a,o,l){super(e,t,i,r,n),this.useVertexColor=a,this.useVertexAlpha=o,this.color=new Re(1,1,1),this.alpha=1,this._shaderLanguage=0,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;const c=[],u={attributes:[$.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:c,useClipPlane:null,shaderLanguage:0};o===!1?u.needAlphaBlending=!1:u.defines.push("#define VERTEXALPHA"),a?(u.defines.push("#define VERTEXCOLOR"),u.attributes.push($.ColorKind)):(u.uniforms.push("color"),this._color4=new Ze),l?this.material=l:(this.getScene().getEngine().isWebGPU&&!Jm.ForceGLSL&&(this._shaderLanguage=1),u.shaderLanguage=this._shaderLanguage,u.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>yMt),void 0),Ue(()=>Promise.resolve().then(()=>vMt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>ubt),void 0),Ue(()=>Promise.resolve().then(()=>obt),void 0)])},this.material=new na("colorShader",this.getScene(),"color",u,!1),this.material.doNotSerialize=!0)}isReady(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)?super.isReady():!1}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=Ye.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r,g:n,b:a}=this.color;this._color4.set(r,n,a,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Ye.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Ye.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Jm(e,this.getScene(),t,this,i)}createInstance(e){const t=new s1e(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Jm(e.name,t);return i.color=Re.FromArray(e.color),i.alpha=e.alpha,i}}Jm.ForceGLSL=!1;class s1e extends C0{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function n1e(s){const e=[],t=[],i=s.lines,r=s.colors,n=[];let a=0;for(let l=0;l0&&(e.push(a-1),e.push(a)),a++}}const o=new at;return o.indices=e,o.positions=t,r&&(o.colors=n),o}function a1e(s){const e=s.dashSize||3,t=s.gapSize||1,i=s.dashNb||200,r=s.points,n=[],a=[],o=D.Zero();let l=0,c=0,u=0,h=0,d=0,f=0,p=0;for(p=0;p{const h=D.Zero(),d=u.length/6;let f=0,p=0,m=0,g=0,_=0,y=0,v=0,x=0;for(v=0;vdn(s,{points:e,updatable:i,instance:r},t);Ee.CreateDashedLines=(s,e,t,i,r,n=null,a,o)=>tee(s,{points:e,dashSize:t,gapSize:i,dashNb:r,updatable:a,instance:o},n);class Xvt extends we{constructor(e,t){super(e.x,e.y),this.index=t}}class wne{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const r=new Xvt(i,this.elements.length);t.push(r),this.elements.push(r)}),t}computeBounds(){const e=new we(this.elements[0].x,this.elements[0].y),t=new we(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}let Yvt=class{static Rectangle(e,t,i,r){return[new we(e,t),new we(i,t),new we(i,r),new we(e,r)]}static Circle(e,t=0,i=0,r=32){const n=[];let a=0;const o=Math.PI*2/r;for(let l=0;l!isNaN(n));let i;const r=[];for(i=0;i<(t.length&2147483646);i+=2)r.push(new we(t[i],t[i+1]));return r}static StartingAt(e,t){return Qw.StartingAt(e,t)}};class yke{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){this._points=new wne,this._outlinepoints=new wne,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||Rt.LastCreatedScene;let n;t instanceof Qw?n=t.getPoints():n=t,this._addToepoint(n),this._points.add(n),this._outlinepoints.add(n),typeof this.bjsEarcut>"u"&&fe.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new wne;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const r=new Ee(this._name,this._scene),n=this.buildVertexData(t,i);return r.setVerticesData($.PositionKind,n.positions,e),r.setVerticesData($.NormalKind,n.normals,e),r.setVerticesData($.UVKind,n.uvs,e),r.setIndices(n.indices),r}buildVertexData(e=0,t=2){const i=new at,r=[],n=[],a=[],o=this._points.computeBounds();this._points.elements.forEach(u=>{r.push(0,1,0),n.push(u.x,0,u.y),a.push((u.x-o.min.x)/o.width,(u.y-o.min.y)/o.height)});const l=[],c=this.bjsEarcut(this._epoints,this._eholes,2);for(let u=0;u0){const u=n.length/3;this._points.elements.forEach(d=>{r.push(0,-1,0),n.push(d.x,-e,d.y),a.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height)});const h=l.length;for(let d=0;d{this._addSide(n,r,a,l,o,d,e,!0,t)})}return i.indices=l,i.positions=n,i.normals=r,i.uvs=a,i}_addSide(e,t,i,r,n,a,o,l,c){let u=e.length/3,h=0;for(let d=0;dc?Cc?TNz(s,{shape:e,holes:i,updatable:r,sideOrientation:n},t,a);Ee.ExtrudePolygon=(s,e,t,i,r,n,a,o=earcut)=>Fz(s,{shape:e,holes:r,depth:t,updatable:n,sideOrientation:a},i,o);function Bz(s,e,t=null){const i=e.path,r=e.shape,n=e.scale||1,a=e.rotation||0,o=e.cap===0?0:e.cap||Ee.NO_CAP,l=e.updatable,c=Ee._GetDefaultSideOrientation(e.sideOrientation),u=e.instance||null,h=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return xke(s,r,i,n,a,null,null,f,d,o,!1,t,!!l,c,u,h,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function kz(s,e,t=null){const i=e.path,r=e.shape,n=e.scaleFunction||(()=>1),a=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,c=e.cap===0?0:e.cap||Ee.NO_CAP,u=e.updatable,h=e.firstNormal||null,d=e.adjustFrame||!1,f=Ee._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,m=e.invertUV||!1;return xke(s,r,i,null,null,n,a,o,l,c,!0,t,!!u,f,p||null,m,e.frontUVs||null,e.backUVs||null,h,d)}function xke(s,e,t,i,r,n,a,o,l,c,u,h,d,f,p,m,g,_,y,v){const x=(w,P,M,R,I,L,k,V,H,j,z)=>{const K=M.getTangents(),U=M.getNormals(),W=M.getBinormals(),Z=M.getDistances();if(z){for(let te=0;te0){let oe=K[te-1];D.Dot(oe,K[te])<0&&K[te].scaleInPlace(-1),oe=U[te-1],D.Dot(oe,U[te])<0&&U[te].scaleInPlace(-1),oe=W[te-1],D.Dot(oe,W[te])<0&&W[te].scaleInPlace(-1)}}let q=0;const ie=()=>I!==null?I:1,ue=j&&V?V:()=>L!==null?L:0,ce=j&&k?k:ie;let N=H===Ee.NO_CAP||H===Ee.CAP_END?0:2;const B=se.Matrix[0];for(let te=0;te{const oe=Array(),ne=D.Zero();let pe;for(pe=0;pe3?0:c,b=x(e,t,A,C,i,r,n,a,c,u,v);const T=c_(s,{pathArray:b,closeArray:o,closePath:l,updatable:d,sideOrientation:f,invertUV:m,frontUVs:g||void 0,backUVs:_||void 0},h);return T._creationDataStorage.pathArray=b,T._creationDataStorage.path3D=A,T._creationDataStorage.cap=c,T}const $vt={ExtrudeShape:Bz,ExtrudeShapeCustom:kz};Ee.ExtrudeShape=(s,e,t,i,r,n,a=null,o,l,c)=>{const u={shape:e,path:t,scale:i,rotation:r,cap:n===0?0:n||Ee.NO_CAP,sideOrientation:l,instance:c,updatable:o};return Bz(s,u,a)};Ee.ExtrudeShapeCustom=(s,e,t,i,r,n,a,o,l,c,u,h)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:a,cap:o===0?0:o||Ee.NO_CAP,sideOrientation:u,instance:h,updatable:c};return kz(s,d,l)};function iee(s,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,r=e.closed===void 0?!0:e.closed,n=e.shape,a=e.radius||1,o=e.tessellation||64,l=e.clip||0,c=e.updatable,u=Ee._GetDefaultSideOrientation(e.sideOrientation),h=e.cap||Ee.NO_CAP,d=Math.PI*2,f=[],p=e.invertUV||!1;let m=0,g=0;const _=d/o*i;let y,v;for(m=0;m<=o-l;m++){for(v=[],(h==Ee.CAP_START||h==Ee.CAP_ALL)&&(v.push(new D(0,n[0].y,0)),v.push(new D(Math.cos(m*_)*n[0].x*a,n[0].y,Math.sin(m*_)*n[0].x*a))),g=0;giee(s,{shape:e,radius:t,tessellation:i,sideOrientation:a,updatable:n},r);function ree(s,e,t=null){const i=e.path;let r=e.instance,n=1;e.radius!==void 0?n=e.radius:r&&(n=r._creationDataStorage.radius);const a=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||Ee.NO_CAP;const c=e.invertUV||!1,u=e.updatable,h=Ee._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(_,y,v,x,A,b,C,T)=>{const w=y.getTangents(),P=y.getNormals(),M=y.getDistances(),I=Math.PI*2/A*T,k=b||(()=>x);let V,H,j,z;const K=se.Matrix[0];let U=C===Ee.NO_CAP||C===Ee.CAP_END?0:2;for(let Z=0;Z<_.length;Z++){H=k(Z,M[Z]),V=Array(),j=P[Z];for(let q=0;q{const ie=Array();for(let ae=0;ae3?0:l,p=d(i,f,m,n,a,o,l,e.arc);const g=c_(s,{pathArray:p,closePath:!0,closeArray:!1,updatable:u,sideOrientation:h,invertUV:c,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return g._creationDataStorage.pathArray=p,g._creationDataStorage.path3D=f,g._creationDataStorage.tessellation=a,g._creationDataStorage.cap=l,g._creationDataStorage.arc=e.arc,g._creationDataStorage.radius=n,g}const qvt={CreateTube:ree};Ee.CreateTube=(s,e,t,i,r,n,a,o,l,c)=>ree(s,{path:e,radius:t,tessellation:i,radiusFunction:r,arc:1,cap:n,updatable:o,sideOrientation:l,instance:c},a);function l1e(s){const e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const t=s.type&&(s.type<0||s.type>=e.length)?0:s.type||0,i=s.size,r=s.sizeX||i||1,n=s.sizeY||i||1,a=s.sizeZ||i||1,o=s.custom||e[t],l=o.face.length,c=s.faceUV||new Array(l),u=s.faceColors,h=s.flat===void 0?!0:s.flat,d=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,f=[],p=[],m=[],g=[],_=[];let y=0,v=0;const x=[];let A=0,b=0,C,T,w,P,M,R;if(h)for(b=0;bn6(s,e,t);function see(s){const e=s.sideOrientation||at.DEFAULTSIDE,t=s.radius||1,i=s.flat===void 0?!0:s.flat,r=(s.subdivisions||4)|0,n=s.radiusX||t,a=s.radiusY||t,o=s.radiusZ||t,l=(1+Math.sqrt(5))/2,c=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],u=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],h=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],f=138/1024,p=239/1024,m=60/1024,g=26/1024,_=-40/1024,y=20/1024,v=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],x=[],A=[],b=[],C=[];let T=0;const w=new Array(3),P=new Array(3);let M;for(M=0;M<3;M++)w[M]=D.Zero(),P[M]=we.Zero();for(let I=0;I<20;I++){for(M=0;M<3;M++){const k=u[3*I+M];w[M].copyFromFloats(c[3*h[k]],c[3*h[k]+1],c[3*h[k]+2]),w[M].normalize(),P[M].copyFromFloats(d[2*k]*f+m+v[I]*_,d[2*k+1]*p+g+v[I]*y)}const L=(k,V,H,j)=>{const z=D.Lerp(w[0],w[2],V/r),K=D.Lerp(w[1],w[2],V/r),U=r===V?w[2]:D.Lerp(z,K,k/(r-V));U.normalize();let W;if(i){const ae=D.Lerp(w[0],w[2],j/r),ue=D.Lerp(w[1],w[2],j/r);W=D.Lerp(ae,ue,H/(r-j))}else W=new D(U.x,U.y,U.z);W.x/=n,W.y/=a,W.z/=o,W.normalize();const Z=we.Lerp(P[0],P[2],V/r),q=we.Lerp(P[1],P[2],V/r),ie=r===V?P[2]:we.Lerp(Z,q,k/(r-V));A.push(U.x*n,U.y*a,U.z*o),b.push(W.x,W.y,W.z),C.push(ie.x,Qr?1-ie.y:ie.y),x.push(T),T++};for(let k=0;kUz(s,e,t);const t3t=new D(1,0,0),i3t=new D(-1,0,0),r3t=new D(0,1,0),s3t=new D(0,-1,0),n3t=new D(0,0,1),a3t=new D(0,0,-1);class dZ{constructor(e=D.Zero(),t=D.Up(),i=we.Zero(),r=0,n=0,a=null,o=null,l=null,c=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=n,this.localPositionOverride=a,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=c}clone(){var e,t,i,r;return new dZ(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(r=this.matrixWeightsOverride)==null?void 0:r.slice())}}function nee(s,e,t){var V,H,j,z;const i=!!e.skeleton,r=t.localMode||i,n=e.getIndices(),a=i?e.getPositionData(!0,!0):e.getVerticesData($.PositionKind),o=i?e.getNormalsData(!0,!0):e.getVerticesData($.NormalKind),l=r?i?e.getVerticesData($.PositionKind):a:null,c=r?i?e.getVerticesData($.NormalKind):o:null,u=e.getVerticesData($.UVKind),h=i?e.getVerticesData($.MatricesIndicesKind):null,d=i?e.getVerticesData($.MatricesWeightsKind):null,f=i?e.getVerticesData($.MatricesIndicesExtraKind):null,p=i?e.getVerticesData($.MatricesWeightsExtraKind):null,m=t.position||D.Zero();let g=t.normal||D.Up();const _=t.size||D.One(),y=t.angle||0;if(!g){const K=new D(0,0,1),U=e.getScene().activeCamera,W=D.TransformCoordinates(K,U.getWorldMatrix());g=U.globalPosition.subtract(W)}const v=-Math.atan2(g.z,g.x)-Math.PI/2,x=Math.sqrt(g.x*g.x+g.z*g.z),A=Math.atan2(g.y,x),b=new at;b.indices=[],b.positions=[],b.normals=[],b.uvs=[],b.matricesIndices=i?[]:null,b.matricesWeights=i?[]:null,b.matricesIndicesExtra=f?[]:null,b.matricesWeightsExtra=p?[]:null;let C=0;const T=(K,U)=>{const W=new dZ;if(!n||!a||!o)return W;const Z=n[K];if(W.vertexIdx=Z*3,W.vertexIdxForBones=Z*4,W.position=new D(a[Z*3],a[Z*3+1],a[Z*3+2]),D.TransformCoordinatesToRef(W.position,U,W.position),W.normal=new D(o[Z*3],o[Z*3+1],o[Z*3+2]),D.TransformNormalToRef(W.normal,U,W.normal),t.captureUVS&&u){const q=u[Z*2+1];W.uv=new we(u[Z*2],Qr?1-q:q)}return W},w=[0,0,0,0],P=(K,U)=>{if(K.length===0)return K;const W=.5*Math.abs(D.Dot(_,U)),Z=(ae,ue,ce,N)=>{for(let B=0;B{const ce=D.GetClipFactor(ae.position,ue.position,U,W);let N=w,B=w;if(h&&d){const hi=ae.matrixIndicesOverride?0:ae.vertexIdxForBones,hr=ae.matrixIndicesOverride??h,tr=ae.matrixWeightsOverride??d,Jr=ue.matrixIndicesOverride?0:ue.vertexIdxForBones,Ti=ue.matrixIndicesOverride??h,Yi=ue.matrixWeightsOverride??d;N=[0,0,0,0],B=[0,0,0,0];let Si=0;for(let Hi=0;Hi<4;++Hi)if(tr[hi+Hi]>0){const er=Z(Ti,hr[hi+Hi],Jr,4);N[Si]=hr[hi+Hi],B[Si]=At.Lerp(tr[hi+Hi],er>=0?Yi[er]:0,ce),Si++}for(let Hi=0;Hi<4&&Si<4;++Hi){const er=Ti[Jr+Hi];Z(hr,er,hi,4)===-1&&(N[Si]=er,B[Si]=At.Lerp(0,Yi[Jr+Hi],ce),Si++)}const dr=B[0]+B[1]+B[2]+B[3];B[0]/=dr,B[1]/=dr,B[2]/=dr,B[3]/=dr}const Y=ae.localPositionOverride?ae.localPositionOverride[0]:(l==null?void 0:l[ae.vertexIdx])??0,te=ae.localPositionOverride?ae.localPositionOverride[1]:(l==null?void 0:l[ae.vertexIdx+1])??0,oe=ae.localPositionOverride?ae.localPositionOverride[2]:(l==null?void 0:l[ae.vertexIdx+2])??0,ne=ue.localPositionOverride?ue.localPositionOverride[0]:(l==null?void 0:l[ue.vertexIdx])??0,pe=ue.localPositionOverride?ue.localPositionOverride[1]:(l==null?void 0:l[ue.vertexIdx+1])??0,ye=ue.localPositionOverride?ue.localPositionOverride[2]:(l==null?void 0:l[ue.vertexIdx+2])??0,Ie=ae.localNormalOverride?ae.localNormalOverride[0]:(c==null?void 0:c[ae.vertexIdx])??0,Ne=ae.localNormalOverride?ae.localNormalOverride[1]:(c==null?void 0:c[ae.vertexIdx+1])??0,Ve=ae.localNormalOverride?ae.localNormalOverride[2]:(c==null?void 0:c[ae.vertexIdx+2])??0,nt=ue.localNormalOverride?ue.localNormalOverride[0]:(c==null?void 0:c[ue.vertexIdx])??0,Ke=ue.localNormalOverride?ue.localNormalOverride[1]:(c==null?void 0:c[ue.vertexIdx+1])??0,Et=ue.localNormalOverride?ue.localNormalOverride[2]:(c==null?void 0:c[ue.vertexIdx+2])??0,ft=Ie+(nt-Ie)*ce,Tt=Ne+(Ke-Ne)*ce,Zt=Ve+(Et-Ve)*ce,Ji=Math.sqrt(ft*ft+Tt*Tt+Zt*Zt);return new dZ(D.Lerp(ae.position,ue.position,ce),D.Lerp(ae.normal,ue.normal,ce).normalize(),we.Lerp(ae.uv,ue.uv,ce),-1,-1,l?[Y+(ne-Y)*ce,te+(pe-te)*ce,oe+(ye-oe)*ce]:null,c?[ft/Ji,Tt/Ji,Zt/Ji]:null,N,B)};let ie=null;K.length>3&&(ie=[]);for(let ae=0;ae0,ye=oe>0,Ie=ne>0;switch(ue=(pe?1:0)+(ye?1:0)+(Ie?1:0),ue){case 0:K.length>3?(ie.push(K[ae]),ie.push(K[ae+1]),ie.push(K[ae+2])):ie=K;break;case 1:if(ie=ie??new Array,pe&&(ce=K[ae+1],N=K[ae+2],B=q(K[ae],ce),Y=q(K[ae],N)),ye){ce=K[ae],N=K[ae+2],B=q(K[ae+1],ce),Y=q(K[ae+1],N),ie.push(B),ie.push(N.clone()),ie.push(ce.clone()),ie.push(N.clone()),ie.push(B.clone()),ie.push(Y);break}Ie&&(ce=K[ae],N=K[ae+1],B=q(K[ae+2],ce),Y=q(K[ae+2],N)),ce&&N&&B&&Y&&(ie.push(ce.clone()),ie.push(N.clone()),ie.push(B),ie.push(Y),ie.push(B.clone()),ie.push(N.clone()));break;case 2:ie=ie??new Array,pe||(ce=K[ae].clone(),N=q(ce,K[ae+1]),B=q(ce,K[ae+2]),ie.push(ce),ie.push(N),ie.push(B)),ye||(ce=K[ae+1].clone(),N=q(ce,K[ae+2]),B=q(ce,K[ae]),ie.push(ce),ie.push(N),ie.push(B)),Ie||(ce=K[ae+2].clone(),N=q(ce,K[ae]),B=q(ce,K[ae+1]),ie.push(ce),ie.push(N),ie.push(B));break}}return ie},M=e instanceof Ee?e:null,R=M==null?void 0:M._thinInstanceDataStorage.matrixData,I=(M==null?void 0:M.thinInstanceCount)||1,L=se.Matrix[0];L.copyFrom(he.IdentityReadOnly);for(let K=0;Knee(s,e,{position:t,normal:i,size:r,angle:n});class da{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),fe.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),fe.Warn("y is not an integer, floor(y) used"))}clone(){return new da(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),fe.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),fe.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),fe.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),fe.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=D.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new da(0,0)}}class c1e{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new fZ("icosahedron","Regular",[[0,Co,-1],[-Co,1,0],[-1,0,-Co],[1,0,-Co],[Co,1,0],[0,Co,1],[-1,0,Co],[-Co,-1,0],[0,-Co,-1],[Co,-1,0],[1,0,Co],[0,-Co,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,r=this.n;let n=i,a=1,o=0;r!==0&&(n=At.HCF(i,r)),a=i/n,o=r/n;let l,c,u,h,d;const f=da.Zero(),p=new da(i,r),m=new da(-r,i+r),g=da.Zero(),_=da.Zero(),y=da.Zero();let v=[],x,A,b,C;const T=[],w=this.vertByDist,P=(M,R,I,L)=>{x=M+"|"+I,A=R+"|"+L,x in t||A in t?x in t&&!(A in t)?t[A]=t[x]:A in t&&!(x in t)&&(t[x]=t[A]):(t[x]=e,t[A]=e,e++),w[I][0]>2?T[t[x]]=[-w[I][0],w[I][1],t[x]]:T[t[x]]=[v[w[I][0]],w[I][1],t[x]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let M=0;M<20;M++){if(v=this.IDATA.face[M],u=v[2],h=v[1],d=v[0],b=f.x+"|"+f.y,x=M+"|"+b,x in t||(t[x]=u,T[u]=[v[w[b][0]],w[b][1]]),b=p.x+"|"+p.y,x=M+"|"+b,x in t||(t[x]=h,T[h]=[v[w[b][0]],w[b][1]]),b=m.x+"|"+m.y,x=M+"|"+b,x in t||(t[x]=d,T[d]=[v[w[b][0]],w[b][1]]),l=this.IDATA.edgematch[M][0],c=this.IDATA.edgematch[M][1],c==="B")for(let R=1;R2?T[t[x]]=[-w[b][0],w[b][1],t[x]]:T[t[x]]=[v[w[b][0]],w[b][1],t[x]])}this.closestTo=T,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&r0){const A=At.HCF(e,t),b=e/A,C=t/A;for(let w=1;wA.x-b.x),i.sort((A,b)=>A.y-b.y);const o=new Array(e+t+1),l=new Array(e+t+1);for(let A=0;A{const C=A.clone();return b==="A"&&C.rotateNeg120(e,t),b==="B"&&C.rotate120(e,t),C.x<0?C.y:C.x+C.y},f=[],p=[],m=[],g=[],_={},y=[];let v=-1,x=-1;for(let A=0;AA[2]-b[2]),y.sort((A,b)=>A[3]-b[3]),y.sort((A,b)=>A[1]-b[1]),y.sort((A,b)=>A[0]-b[0]);for(let A=0;At.vecToidx[e+r]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[a][1]>0&&t[i[a][0]].push([a,i[a][1]]):t[12].push([a,i[a][0]]);const r=[];for(let a=0;a<12;a++)r[a]=a;let n=12;for(let a=0;a<12;a++){t[a].sort((o,l)=>o[1]-l[1]);for(let o=0;oa[3]-o[3]);for(let a=0;a0;)n=t[l],this.face[n].indexOf(o)>-1?(a=(this.face[n].indexOf(o)+1)%3,o=this.face[n][a],i.push(o),r.push(n),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){const e=new fZ("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let c=0;c{r=0,n=0,a=0,o=this.face[u];for(let h=0;h<3;h++)l=this.vertex[o[h]],r+=l[0],n+=l[1],a+=l[2];e.vertex[u]=[r/3,n/3,a/3]});return e}static BuildGeodesicData(e){const t=new zz("Geodesic-m-n","Geodesic",[[0,Co,-1],[-Co,1,0],[-1,0,-Co],[1,0,-Co],[Co,1,0],[0,Co,1],[-1,0,Co],[-Co,-1,0],[0,-Co,-1],[Co,-1,0],[1,0,Co],[0,-Co,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let r=0;ri){const c=r;r=i,i=c,fe.Warn("n > m therefore m and n swapped")}const n=new c1e;n.build(i,r);const o={custom:zz.BuildGeodesicData(n),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return n6(s,o,t)}Ee._GoldbergMeshParser=(s,e)=>Vz.Parse(s,e);class Vz extends Ee{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(fe.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(fe.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(fe.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(h=1),c.push(h,d);for(let f=0;f<6;f++)h=a.x+o*Math.cos(l+f*Math.PI/3),d=a.y+o*Math.sin(l+f*Math.PI/3),h<0&&(h=0),h>1&&(h=1),u.push(h,d);for(let f=r;fZe.FromArray(n)),i.faceCenters=i.faceCenters.map(n=>D.FromArray(n)),i.faceZaxis=i.faceZaxis.map(n=>D.FromArray(n)),i.faceXaxis=i.faceXaxis.map(n=>D.FromArray(n)),i.faceYaxis=i.faceYaxis.map(n=>D.FromArray(n));const r=new Vz(e.name,t);return r.goldbergData=i,r}}function bke(s,e){const t=s.size,i=s.sizeX||t||1,r=s.sizeY||t||1,n=s.sizeZ||t||1,a=s.sideOrientation===0?0:s.sideOrientation||at.DEFAULTSIDE,o=[],l=[],c=[],u=[];let h=1/0,d=-1/0,f=1/0,p=-1/0;for(let _=0;_o){const p=l;l=o,o=p,fe.Warn("n > m therefore m and n swapped")}const c=new c1e;c.build(o,l);const u=zz.BuildGeodesicData(c),h=u.toGoldbergPolyhedronData(),d=new Vz(s,t);e.sideOrientation=Ee._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,bke(e,h).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=u.sharedNodes,d.goldbergData.nbUnsharedFaces=u.poleNodes,d.goldbergData.adjacentFaces=u.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let p=0;p0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function c3t(s,e,t,i,r,n){const a=n.glyphs[s]||n.glyphs["?"];if(!a)return null;const o=new l3t(r);if(a.o){const l=a.o.split(" ");for(let c=0,u=l.length;cci&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>ci&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>ci&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:r,axisA:n,axisB:a,perpAxisA:o,perpAxisB:l}=e._initOptions;!i||!r||!n||!a||!o||!l||t.getDescendants(!0).forEach(c=>{const u=c.getDescendants(!0)[0],h=c.getDescendants(!0)[1],{parentBody:d,parentBodyIndex:f}=u.metadata,{childBody:p,childBodyIndex:m}=h.metadata,g=this._getTransformFromBodyToRef(d,se.Matrix[0],f),_=this._getTransformFromBodyToRef(p,se.Matrix[1],m);g.decomposeToTransformNode(u),this._makeScalingUnitInPlace(u.scaling),_.decomposeToTransformNode(h),this._makeScalingUnitInPlace(h.scaling);const y=u.getDescendants(!0)[0];y.position.copyFrom(i);const v=h.getDescendants(!0)[0];v.position.copyFrom(r),Pe.FromRotationMatrixToRef(he.FromXYZAxesToRef(n,o,D.CrossToRef(n,o,se.Vector3[0]),se.Matrix[0]),y.rotationQuaternion),Pe.FromRotationMatrixToRef(he.FromXYZAxesToRef(a,l,D.CrossToRef(a,l,se.Vector3[1]),se.Matrix[1]),v.rotationQuaternion)})}showImpostor(e,t){if(!this._scene)return null;for(let r=0;rthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let i=0;ithis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let i=0;ithis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let i=0;ithis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r-1&&this._debugMeshMeshes.splice(a,1),this._numMeshes--,this._numMeshes>0?(this._meshes[r]=this._meshes[this._numMeshes],this._impostors[r]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&this._numMeshes===0&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return!1;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._bodyMeshes[r]=this._bodyMeshes[this._numBodies],this._bodies[r]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}return t&&this._numBodies===0&&this._scene.unregisterBeforeRender(this._renderFunction),t}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return!1;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._constraints[r]=this._constraints[this._numConstraints],this._constraintMeshes[r]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&this._numConstraints===0&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new et("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Re.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new et("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=ph("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=Pe.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=kc("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=Pe.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=Oz("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=Pe.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=ou("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=Pe.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Ee(e.name,t,null,e);return i.setParent(e),i.position=D.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer||t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const r=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return fe.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case oi.BoxImpostor:i=this._getDebugBoxMesh(r),e.getBoxSizeToRef(i.scaling);break;case oi.SphereImpostor:{i=this._getDebugSphereMesh(r);const n=e.getRadius();i.scaling.x=n*2,i.scaling.y=n*2,i.scaling.z=n*2;break}case oi.CapsuleImpostor:{i=this._getDebugCapsuleMesh(r);const n=e.object.getBoundingInfo();i.scaling.x=(n.boundingBox.maximum.x-n.boundingBox.minimum.x)*2*e.object.scaling.x,i.scaling.y=(n.boundingBox.maximum.y-n.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(n.boundingBox.maximum.z-n.boundingBox.minimum.z)*2*e.object.scaling.z;break}case oi.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,r));break;case oi.NoImpostor:t?t.getChildMeshes().filter(a=>a.physicsImpostor?1:0).forEach(a=>{if(a.physicsImpostor&&a.getClassName()==="Mesh"){const o=a.getBoundingInfo(),l=o.boundingBox.minimum,c=o.boundingBox.maximum;switch(a.physicsImpostor.type){case oi.BoxImpostor:i=this._getDebugBoxMesh(r),i.position.copyFrom(l),i.position.addInPlace(c),i.position.scaleInPlace(.5);break;case oi.SphereImpostor:i=this._getDebugSphereMesh(r);break;case oi.CylinderImpostor:i=this._getDebugCylinderMesh(r);break;default:i=null;break}i&&(i.scaling.x=c.x-l.x,i.scaling.y=c.y-l.y,i.scaling.z=c.z-l.z,i.parent=a)}}):fe.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case oi.CylinderImpostor:{i=this._getDebugCylinderMesh(r);const n=e.object.getBoundingInfo();i.scaling.x=(n.boundingBox.maximum.x-n.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(n.boundingBox.maximum.y-n.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(n.boundingBox.maximum.z-n.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Ee("custom",t),r=new at,n=e.getGeometry();if(r.positions=n.positions,r.indices=n.indices,r.applyToMesh(i),e._pluginDataInstances){const a=new Float32Array(e._pluginDataInstances.length*16);i.thinInstanceSetBuffer("matrix",a,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??Pe.Identity(),r=e.inertia??D.Zero(),n=e.centerOfMass??D.Zero(),a=(r.x-r.y+r.z)*6,o=Math.sqrt(Math.max(a,0)),l=r.x*12-a,c=Math.sqrt(Math.max(l,0)),u=r.z*12-a,h=Math.sqrt(Math.max(u,0)),d=se.Vector3[0];d.set(h,o,c);const f=he.ScalingToRef(d.x,d.y,d.z,se.Matrix[0]),p=i.toRotationMatrix(se.Matrix[1]),m=he.TranslationToRef(n.x,n.y,n.z,se.Matrix[2]);return f.multiplyToRef(p,t),t.multiplyToRef(m,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=Xh.CreateBox("custom",{size:1},t),r=he.Identity();if(e._pluginDataInstances.length){const n=new Float32Array(e._pluginDataInstances.length*16);for(let a=0;a=0?he.FromArrayToRef(r._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(r.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:r,axisA:n,axisB:a,perpAxisA:o,perpAxisB:l}=e._initOptions;if(!i||!r||!n||!a||!o||!l)return null;const c=new Ee("parentingDebugConstraint",t),u=e.getBodiesUsingConstraint();for(const h of u){const d=new _t("parentOfPair",t);d.parent=c;const{parentBody:f,parentBodyIndex:p,childBody:m,childBodyIndex:g}=h,_=this._getTransformFromBodyToRef(f,se.Matrix[0],p),y=this._getTransformFromBodyToRef(m,se.Matrix[1],g),v=new _t("parentCoordSystem",t);v.parent=d,v.metadata={parentBody:f,parentBodyIndex:p},_.decomposeToTransformNode(v);const x=new _t("childCoordSystem",t);x.parent=d,x.metadata={childBody:m,childBodyIndex:g},y.decomposeToTransformNode(x);const A=Pe.FromRotationMatrix(he.FromXYZAxesToRef(n,o,n.cross(o),se.Matrix[0])),b=Pe.FromRotationMatrix(he.FromXYZAxesToRef(a,l,a.cross(l),se.Matrix[0])),C=i,T=r,w=new _t("constraint_parent",t);w.position.copyFrom(C),w.rotationQuaternion=A,w.parent=v;const P=new _t("constraint_child",t);P.parent=x,P.position.copyFrom(T),P.rotationQuaternion=b;const M=new hv(t,this._constraintAxesSize);M.xAxis.parent=w,M.yAxis.parent=w,M.zAxis.parent=w;const R=new hv(t,this._constraintAxesSize);R.xAxis.parent=P,R.yAxis.parent=P,R.zAxis.parent=P}return c}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class h1e{static CreateAndShow(e,t,i){const r=new h1e(e);return r.show(t,i),r}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const i=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[i.origin,i.origin.add(i.direction.scale(i.length))],this._renderLine=dn("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){var r;const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),dn("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),(r=this._renderLine)==null||r.refreshBoundingInfo()}attachToMesh(e,t,i,r){this._attachedToMesh=e;const n=this.ray;n&&(n.direction||(n.direction=D.Zero()),n.origin||(n.origin=D.Zero()),r&&(n.length=r),i||(i=D.Zero()),t||(t=new D(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add(()=>this._updateToMesh()),this._onAfterStepObserver=this._scene.onAfterStepObservable.add(()=>this._updateToMesh())),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;if(!(!this._attachedToMesh||!e)){if(this._attachedToMesh.isDisposed()){this.detachFromMesh();return}this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),D.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)}}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class ch{static CreateBoneWeightShader(e,t){const i=e.skeleton,r=e.colorBase??Re.Black(),n=e.colorZero??Re.Blue(),a=e.colorQuarter??Re.Green(),o=e.colorHalf??Re.Yellow(),l=e.colorFull??Re.Red(),c=e.targetBoneIndex??0;zi.ShadersStore["boneWeights:"+i.name+"VertexShader"]=`precision highp float; attribute vec3 position; attribute vec2 uv; uniform mat4 view; uniform mat4 projection; uniform mat4 worldViewProjection; #include #if NUM_BONE_INFLUENCERS == 0 attribute vec4 matricesIndices; attribute vec4 matricesWeights; #endif #include #include varying vec3 vColor; uniform vec3 colorBase; uniform vec3 colorZero; uniform vec3 colorQuarter; uniform vec3 colorHalf; uniform vec3 colorFull; uniform float targetBoneIndex; void main() { vec3 positionUpdated = position; #include #include #include vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); vec3 color = colorBase; float totalWeight = 0.; if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ totalWeight += matricesWeights[0]; } if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ totalWeight += matricesWeights[1]; } if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ totalWeight += matricesWeights[2]; } if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ totalWeight += matricesWeights[3]; } color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); vColor = color; gl_Position = projection * view * worldPos; }`,zi.ShadersStore["boneWeights:"+i.name+"FragmentShader"]=` precision highp float; varying vec3 vPosition; varying vec3 vColor; void main() { vec4 color = vec4(vColor, 1.0); gl_FragColor = color; } `;const u=new na("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return u.setColor3("colorBase",r),u.setColor3("colorZero",n),u.setColor3("colorQuarter",a),u.setColor3("colorHalf",o),u.setColor3("colorFull",l),u.setFloat("targetBoneIndex",c),u.getClassName=()=>"BoneWeightShader",u.transparencyMode=Ye.MATERIAL_OPAQUE,u}static CreateSkeletonMapShader(e,t){const i=e.skeleton,r=e.colorMap??[{color:new Re(1,.38,.18),location:0},{color:new Re(.59,.18,1),location:.2},{color:new Re(.59,1,.18),location:.4},{color:new Re(1,.87,.17),location:.6},{color:new Re(1,.17,.42),location:.8},{color:new Re(.17,.68,1),location:1}],n=i.bones.length+1,a=ch._CreateBoneMapColorBuffer(n,r,t),o=new na("boneWeights:"+i.name,t,{vertexSource:`precision highp float; attribute vec3 position; attribute vec2 uv; uniform mat4 view; uniform mat4 projection; uniform mat4 worldViewProjection; uniform float colorMap[`+i.bones.length*4+`]; #include #if NUM_BONE_INFLUENCERS == 0 attribute vec4 matricesIndices; attribute vec4 matricesWeights; #endif #include #include varying vec3 vColor; void main() { vec3 positionUpdated = position; #include #include #include vec3 color = vec3(0.); bool first = true; for (int i = 0; i < 4; i++) { int boneIdx = int(matricesIndices[i]); float boneWgt = matricesWeights[i]; vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); if (boneWgt > 0.) { if (first) { first = false; color = c; } else { color = mix(color, c, boneWgt); } } } vColor = color; vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); gl_Position = projection * view * worldPos; }`,fragmentSource:` precision highp float; varying vec3 vColor; void main() { vec4 color = vec4( vColor, 1.0 ); gl_FragColor = color; } `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=Ye.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const r=new Qf("temp",{width:e,height:1},i,!1),n=r.getContext(),a=n.createLinearGradient(0,0,e,0);t.forEach(u=>{a.addColorStop(u.location,u.color.toHexString())}),n.fillStyle=a,n.fillRect(0,0,e,1),r.update();const o=[],l=n.getImageData(0,0,e,1).data,c=1/255;for(let u=0;uch.DISPLAY_SPHERE_AND_SPURS&&(e=ch.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,n=3,a={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=n,this.options=a,this.color=Re.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,a.pauseAnimations=a.pauseAnimations??!0,a.returnToRest=a.returnToRest??!1,a.displayMode=a.displayMode??ch.DISPLAY_LINES,a.displayOptions=a.displayOptions??{},a.displayOptions.midStep=a.displayOptions.midStep??.235,a.displayOptions.midStepFactor=a.displayOptions.midStepFactor??.155,a.displayOptions.sphereBaseSize=a.displayOptions.sphereBaseSize??.15,a.displayOptions.sphereScaleUnit=a.displayOptions.sphereScaleUnit??2,a.displayOptions.sphereFactor=a.displayOptions.sphereFactor??.865,a.displayOptions.spurFollowsChild=a.displayOptions.spurFollowsChild??!1,a.displayOptions.showLocalAxes=a.displayOptions.showLocalAxes??!1,a.displayOptions.localAxesSize=a.displayOptions.localAxesSize??.075,a.computeBonesUsingShaders=a.computeBonesUsingShaders??!0,a.useAllBones=a.useAllBones??!0,this._boneIndices=new Set,!a.useAllBones){const l=t==null?void 0:t.getVerticesData($.MatricesIndicesKind),c=t==null?void 0:t.getVerticesData($.MatricesWeightsKind);if(l&&c)for(let u=0;uch.DISPLAY_SPHERE_AND_SPURS&&(o=ch.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){switch(this.displayMode){case ch.DISPLAY_LINES:{this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()});break}}}update(){switch(this.displayMode){case ch.DISPLAY_LINES:{this._displayLinesUpdate();break}case ch.DISPLAY_SPHERES:{this._buildSpheresAndSpurs(!0);break}case ch.DISPLAY_SPHERE_AND_SPURS:{this._buildSpheresAndSpurs(!1);break}}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,n=0,a=0){const o=se.Matrix[0],l=t.getParent();if(o.copyFrom(t.getLocalMatrix()),r!==0||n!==0||a!==0){const c=se.Matrix[1];he.IdentityToRef(c),c.setTranslationFromFloats(r,n,a),c.multiplyToRef(o,o)}l&&o.multiplyToRef(l.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let r,n;t?(r=t.getWorldMatrix(),n=t.position):(r=new he,n=e[0].position);let a=0;for(let o=0;o=0;o--){const l=e[o],c=l.getParent();if(!c||!this._boneIndices.has(l.getIndex())&&!this.options.useAllBones)continue;let u=this._debugLines[i];u||(u=[D.Zero(),D.Zero()],this._debugLines[i]=u),l.getAbsolutePositionToRef(n,u[0]),c.getAbsolutePositionToRef(n,u[1]),u[0].subtractInPlace(a),u[1].subtractInPlace(a),i++}r||n.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(e===null||e._index===-1){t.copyFrom(he.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_createSpur(e,t,i,r,n,a){const o=i.subtract(e),l=o.length(),c=o.normalize().scale(l),u=n.midStep||.165,h=n.midStepFactor||.215,d=c.scale(u),f=kz("skeletonViewer",{shape:[new D(1,-1,0),new D(1,1,0),new D(-1,1,0),new D(-1,-1,0),new D(1,-1,0)],path:[D.Zero(),d,c],scaleFunction:_=>{switch(_){case 0:case 2:return 0;case 1:return l*h}return 0},sideOrientation:Ee.DEFAULTSIDE,updatable:!1},a),p=f.getTotalVertices(),m=[],g=[];for(let _=0;_9?g.push(r.getIndex(),0,0,0):g.push(t.getIndex(),0,0,0);return f.position=e.clone(),f.setVerticesData($.MatricesWeightsKind,m,!1),f.setVerticesData($.MatricesIndicesKind,g,!1),f.convertToFlatShadedMesh(),f}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData($.PositionKind),i=this.mesh.getIndices(),r=this.mesh.getVerticesData($.MatricesWeightsKind),n=this.mesh.getVerticesData($.MatricesIndicesKind);if(!t||!i||!r||!n)return null;const a=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let l=0;for(let c=0;c1e-5){D.FromArrayToRef(t,u*3,se.Vector3[0]),a.minimizeInPlace(se.Vector3[0]),o.maximizeInPlace(se.Vector3[0]),l++;break}}}return l>1?{center:D.Center(a,o),radius:D.Distance(a,o)/2}:null}_buildSpheresAndSpurs(e=!0){var o;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=(o=this.utilityLayer)==null?void 0:o.utilityLayerScene,i=this.skeleton.bones,r=[],n=[],a=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let l=Number.NEGATIVE_INFINITY;const c=this.options.displayOptions||{};for(let p=0;p0)m.children.forEach(C=>{const T=new he;C.getLocalMatrix().multiplyToRef(g,T);const w=new D;T.decompose(void 0,void 0,w);const P=D.Distance(_,w);P>l&&(l=P),!e&&n.push(this._createSpur(_,m,w,C,c,t))});else{const C=this._getBoundingSphereForBone(m.getIndex());if(C&&(C.radius>l&&(l=C.radius),!e)){let T;const w=m.getParent();w?(this._getAbsoluteBindPoseToRef(w,g),g.decompose(void 0,void 0,se.Vector3[0]),T=_.subtract(se.Vector3[0]).normalize().scale(C.radius).add(_)):T=C.center.subtract(_).normalize().scale(C.radius).add(_),n.push(this._createSpur(_,m,T,null,c,t))}}const y=c.sphereBaseSize||.2,v=kc("skeletonViewer",{segments:6,diameter:y,updatable:!0},t),x=v.getTotalVertices(),A=[],b=[];for(let C=0;C{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)}),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach(e=>{e.setEnabled(!1)}),this._visible=!1}update(){var t,i,r,n,a,o;if(!this._visible||this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,se.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,this._light.shadowMinZ!==void 0?this._light.shadowMinZ:this._camera.minZ),se.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,this._light.shadowMaxZ!==void 0?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();se.Vector3[2].copyFromFloats(se.Vector3[1].x,se.Vector3[1].y,se.Vector3[0].z),se.Vector3[3].copyFromFloats(se.Vector3[1].x,se.Vector3[0].y,se.Vector3[0].z),se.Vector3[4].copyFromFloats(se.Vector3[0].x,se.Vector3[0].y,se.Vector3[0].z),se.Vector3[5].copyFromFloats(se.Vector3[0].x,se.Vector3[1].y,se.Vector3[0].z),D.TransformCoordinatesToRef(se.Vector3[2],e,se.Vector3[2]),D.TransformCoordinatesToRef(se.Vector3[3],e,se.Vector3[3]),D.TransformCoordinatesToRef(se.Vector3[4],e,se.Vector3[4]),D.TransformCoordinatesToRef(se.Vector3[5],e,se.Vector3[5]),se.Vector3[6].copyFromFloats(se.Vector3[1].x,se.Vector3[1].y,se.Vector3[1].z),se.Vector3[7].copyFromFloats(se.Vector3[1].x,se.Vector3[0].y,se.Vector3[1].z),se.Vector3[8].copyFromFloats(se.Vector3[0].x,se.Vector3[0].y,se.Vector3[1].z),se.Vector3[9].copyFromFloats(se.Vector3[0].x,se.Vector3[1].y,se.Vector3[1].z),D.TransformCoordinatesToRef(se.Vector3[6],e,se.Vector3[6]),D.TransformCoordinatesToRef(se.Vector3[7],e,se.Vector3[7]),D.TransformCoordinatesToRef(se.Vector3[8],e,se.Vector3[8]),D.TransformCoordinatesToRef(se.Vector3[9],e,se.Vector3[9]),dn("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),dn("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),dn("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),dn("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),dn("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),dn("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),se.Vector3[2].toArray(this._nearPlaneVertices,0),se.Vector3[3].toArray(this._nearPlaneVertices,3),se.Vector3[4].toArray(this._nearPlaneVertices,6),se.Vector3[5].toArray(this._nearPlaneVertices,9),(t=this._lightHelperFrustumMeshes[6].geometry)==null||t.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),se.Vector3[6].toArray(this._farPlaneVertices,0),se.Vector3[7].toArray(this._farPlaneVertices,3),se.Vector3[8].toArray(this._farPlaneVertices,6),se.Vector3[9].toArray(this._farPlaneVertices,9),(i=this._lightHelperFrustumMeshes[7].geometry)==null||i.updateVerticesDataDirectly("position",this._farPlaneVertices,0),se.Vector3[2].toArray(this._rightPlaneVertices,0),se.Vector3[6].toArray(this._rightPlaneVertices,3),se.Vector3[7].toArray(this._rightPlaneVertices,6),se.Vector3[3].toArray(this._rightPlaneVertices,9),(r=this._lightHelperFrustumMeshes[8].geometry)==null||r.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),se.Vector3[5].toArray(this._leftPlaneVertices,0),se.Vector3[9].toArray(this._leftPlaneVertices,3),se.Vector3[8].toArray(this._leftPlaneVertices,6),se.Vector3[4].toArray(this._leftPlaneVertices,9),(n=this._lightHelperFrustumMeshes[9].geometry)==null||n.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),se.Vector3[2].toArray(this._topPlaneVertices,0),se.Vector3[6].toArray(this._topPlaneVertices,3),se.Vector3[9].toArray(this._topPlaneVertices,6),se.Vector3[5].toArray(this._topPlaneVertices,9),(a=this._lightHelperFrustumMeshes[10].geometry)==null||a.updateVerticesDataDirectly("position",this._topPlaneVertices,0),se.Vector3[3].toArray(this._bottomPlaneVertices,0),se.Vector3[7].toArray(this._bottomPlaneVertices,3),se.Vector3[8].toArray(this._bottomPlaneVertices,6),se.Vector3[4].toArray(this._bottomPlaneVertices,9),(o=this._lightHelperFrustumMeshes[11].geometry)==null||o.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach(e=>{var t;(t=e.material)==null||t.dispose(),e.dispose()}),this._rootNode.dispose()}_createGeometry(){this._rootNode=new _t("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[se.Vector3[0],se.Vector3[1],se.Vector3[2],se.Vector3[3],se.Vector3[4]];const e=dn("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[se.Vector3[5],se.Vector3[6],se.Vector3[7],se.Vector3[8],se.Vector3[9]];const t=dn("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[se.Vector3[10],se.Vector3[11]];const i=dn("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[se.Vector3[12],se.Vector3[0]];const r=dn("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[se.Vector3[1],se.Vector3[2]];const n=dn("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[se.Vector3[3],se.Vector3[4]];const a=dn("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);a.parent=this._rootNode,a.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,r,n,a);const o=(l,c,u)=>{const h=new Ee(l+"plane",this._scene),d=new et(l+"PlaneMat",this._scene);h.material=d,h.parent=this._rootNode,h.alwaysSelectAsActiveMesh=!0,d.emissiveColor=c,d.alpha=this.transparency,d.backFaceCulling=!1,d.disableLighting=!0;const f=[0,1,2,0,2,3],p=new at;p.positions=u,p.indices=f,p.applyToMesh(h,!0),this._lightHelperFrustumMeshes.push(h)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new Re(1,0,0),this._nearPlaneVertices),o("far",new Re(.3,0,0),this._farPlaneVertices),o("right",new Re(0,1,0),this._rightPlaneVertices),o("left",new Re(0,.3,0),this._leftPlaneVertices),o("top",new Re(0,0,1),this._topPlaneVertices),o("bottom",new Re(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=se.Vector3[2],this._nearLinesPoints[1]=se.Vector3[3],this._nearLinesPoints[2]=se.Vector3[4],this._nearLinesPoints[3]=se.Vector3[5],this._nearLinesPoints[4]=se.Vector3[2],this._farLinesPoints[0]=se.Vector3[6],this._farLinesPoints[1]=se.Vector3[7],this._farLinesPoints[2]=se.Vector3[8],this._farLinesPoints[3]=se.Vector3[9],this._farLinesPoints[4]=se.Vector3[6],this._trLinesPoints[0]=se.Vector3[2],this._trLinesPoints[1]=se.Vector3[6],this._brLinesPoints[0]=se.Vector3[3],this._brLinesPoints[1]=se.Vector3[7],this._tlLinesPoints[0]=se.Vector3[4],this._tlLinesPoints[1]=se.Vector3[8],this._blLinesPoints[0]=se.Vector3[5],this._blLinesPoints[1]=se.Vector3[9]}_getInvertViewMatrix(){return he.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),D.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class Le{}Le.AUTOSAMPLERSUFFIX="Sampler";Le.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS";Le.ALPHA_DISABLE=0;Le.ALPHA_ADD=1;Le.ALPHA_COMBINE=2;Le.ALPHA_SUBTRACT=3;Le.ALPHA_MULTIPLY=4;Le.ALPHA_MAXIMIZED=5;Le.ALPHA_ONEONE=6;Le.ALPHA_PREMULTIPLIED=7;Le.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Le.ALPHA_INTERPOLATE=9;Le.ALPHA_SCREENMODE=10;Le.ALPHA_ONEONE_ONEONE=11;Le.ALPHA_ALPHATOCOLOR=12;Le.ALPHA_REVERSEONEMINUS=13;Le.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;Le.ALPHA_ONEONE_ONEZERO=15;Le.ALPHA_EXCLUSION=16;Le.ALPHA_LAYER_ACCUMULATE=17;Le.ALPHA_EQUATION_ADD=0;Le.ALPHA_EQUATION_SUBSTRACT=1;Le.ALPHA_EQUATION_REVERSE_SUBTRACT=2;Le.ALPHA_EQUATION_MAX=3;Le.ALPHA_EQUATION_MIN=4;Le.ALPHA_EQUATION_DARKEN=5;Le.DELAYLOADSTATE_NONE=0;Le.DELAYLOADSTATE_LOADED=1;Le.DELAYLOADSTATE_LOADING=2;Le.DELAYLOADSTATE_NOTLOADED=4;Le.NEVER=512;Le.ALWAYS=519;Le.LESS=513;Le.EQUAL=514;Le.LEQUAL=515;Le.GREATER=516;Le.GEQUAL=518;Le.NOTEQUAL=517;Le.KEEP=7680;Le.ZERO=0;Le.REPLACE=7681;Le.INCR=7682;Le.DECR=7683;Le.INVERT=5386;Le.INCR_WRAP=34055;Le.DECR_WRAP=34056;Le.TEXTURE_CLAMP_ADDRESSMODE=0;Le.TEXTURE_WRAP_ADDRESSMODE=1;Le.TEXTURE_MIRROR_ADDRESSMODE=2;Le.TEXTURE_CREATIONFLAG_STORAGE=1;Le.TEXTUREFORMAT_ALPHA=0;Le.TEXTUREFORMAT_LUMINANCE=1;Le.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Le.TEXTUREFORMAT_RGB=4;Le.TEXTUREFORMAT_RGBA=5;Le.TEXTUREFORMAT_RED=6;Le.TEXTUREFORMAT_R=6;Le.TEXTUREFORMAT_RG=7;Le.TEXTUREFORMAT_RED_INTEGER=8;Le.TEXTUREFORMAT_R_INTEGER=8;Le.TEXTUREFORMAT_RG_INTEGER=9;Le.TEXTUREFORMAT_RGB_INTEGER=10;Le.TEXTUREFORMAT_RGBA_INTEGER=11;Le.TEXTUREFORMAT_BGRA=12;Le.TEXTUREFORMAT_DEPTH24_STENCIL8=13;Le.TEXTUREFORMAT_DEPTH32_FLOAT=14;Le.TEXTUREFORMAT_DEPTH16=15;Le.TEXTUREFORMAT_DEPTH24=16;Le.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;Le.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;Le.TEXTUREFORMAT_STENCIL8=19;Le.TEXTUREFORMAT_UNDEFINED=4294967295;Le.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;Le.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;Le.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;Le.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;Le.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;Le.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;Le.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;Le.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;Le.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;Le.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;Le.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;Le.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;Le.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;Le.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;Le.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;Le.TEXTURETYPE_UNSIGNED_BYTE=0;Le.TEXTURETYPE_UNSIGNED_INT=0;Le.TEXTURETYPE_FLOAT=1;Le.TEXTURETYPE_HALF_FLOAT=2;Le.TEXTURETYPE_BYTE=3;Le.TEXTURETYPE_SHORT=4;Le.TEXTURETYPE_UNSIGNED_SHORT=5;Le.TEXTURETYPE_INT=6;Le.TEXTURETYPE_UNSIGNED_INTEGER=7;Le.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Le.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Le.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Le.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Le.TEXTURETYPE_UNSIGNED_INT_24_8=12;Le.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Le.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Le.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Le.TEXTURETYPE_UNDEFINED=16;Le.TEXTURE_2D=3553;Le.TEXTURE_2D_ARRAY=35866;Le.TEXTURE_CUBE_MAP=34067;Le.TEXTURE_CUBE_MAP_ARRAY=3735928559;Le.TEXTURE_3D=32879;Le.TEXTURE_NEAREST_SAMPLINGMODE=1;Le.TEXTURE_NEAREST_NEAREST=1;Le.TEXTURE_BILINEAR_SAMPLINGMODE=2;Le.TEXTURE_LINEAR_LINEAR=2;Le.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Le.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Le.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Le.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Le.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Le.TEXTURE_NEAREST_LINEAR=7;Le.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Le.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Le.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Le.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Le.TEXTURE_LINEAR_NEAREST=12;Le.TEXTURE_EXPLICIT_MODE=0;Le.TEXTURE_SPHERICAL_MODE=1;Le.TEXTURE_PLANAR_MODE=2;Le.TEXTURE_CUBIC_MODE=3;Le.TEXTURE_PROJECTION_MODE=4;Le.TEXTURE_SKYBOX_MODE=5;Le.TEXTURE_INVCUBIC_MODE=6;Le.TEXTURE_EQUIRECTANGULAR_MODE=7;Le.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Le.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Le.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;Le.TEXTURE_FILTERING_QUALITY_HIGH=64;Le.TEXTURE_FILTERING_QUALITY_MEDIUM=16;Le.TEXTURE_FILTERING_QUALITY_LOW=8;Le.SCALEMODE_FLOOR=1;Le.SCALEMODE_NEAREST=2;Le.SCALEMODE_CEILING=3;Le.MATERIAL_TextureDirtyFlag=1;Le.MATERIAL_LightDirtyFlag=2;Le.MATERIAL_FresnelDirtyFlag=4;Le.MATERIAL_AttributesDirtyFlag=8;Le.MATERIAL_MiscDirtyFlag=16;Le.MATERIAL_PrePassDirtyFlag=32;Le.MATERIAL_AllDirtyFlag=63;Le.MATERIAL_TriangleFillMode=0;Le.MATERIAL_WireFrameFillMode=1;Le.MATERIAL_PointFillMode=2;Le.MATERIAL_PointListDrawMode=3;Le.MATERIAL_LineListDrawMode=4;Le.MATERIAL_LineLoopDrawMode=5;Le.MATERIAL_LineStripDrawMode=6;Le.MATERIAL_TriangleStripDrawMode=7;Le.MATERIAL_TriangleFanDrawMode=8;Le.MATERIAL_ClockWiseSideOrientation=0;Le.MATERIAL_CounterClockWiseSideOrientation=1;Le.ACTION_NothingTrigger=0;Le.ACTION_OnPickTrigger=1;Le.ACTION_OnLeftPickTrigger=2;Le.ACTION_OnRightPickTrigger=3;Le.ACTION_OnCenterPickTrigger=4;Le.ACTION_OnPickDownTrigger=5;Le.ACTION_OnDoublePickTrigger=6;Le.ACTION_OnPickUpTrigger=7;Le.ACTION_OnPickOutTrigger=16;Le.ACTION_OnLongPressTrigger=8;Le.ACTION_OnPointerOverTrigger=9;Le.ACTION_OnPointerOutTrigger=10;Le.ACTION_OnEveryFrameTrigger=11;Le.ACTION_OnIntersectionEnterTrigger=12;Le.ACTION_OnIntersectionExitTrigger=13;Le.ACTION_OnKeyDownTrigger=14;Le.ACTION_OnKeyUpTrigger=15;Le.PARTICLES_BILLBOARDMODE_Y=2;Le.PARTICLES_BILLBOARDMODE_ALL=7;Le.PARTICLES_BILLBOARDMODE_STRETCHED=8;Le.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;Le.MESHES_CULLINGSTRATEGY_STANDARD=0;Le.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Le.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Le.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;Le.SCENELOADER_NO_LOGGING=0;Le.SCENELOADER_MINIMAL_LOGGING=1;Le.SCENELOADER_SUMMARY_LOGGING=2;Le.SCENELOADER_DETAILED_LOGGING=3;Le.PREPASS_IRRADIANCE_TEXTURE_TYPE=0;Le.PREPASS_POSITION_TEXTURE_TYPE=1;Le.PREPASS_VELOCITY_TEXTURE_TYPE=2;Le.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;Le.PREPASS_COLOR_TEXTURE_TYPE=4;Le.PREPASS_DEPTH_TEXTURE_TYPE=5;Le.PREPASS_NORMAL_TEXTURE_TYPE=6;Le.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;Le.BUFFER_CREATIONFLAG_READ=1;Le.BUFFER_CREATIONFLAG_WRITE=2;Le.BUFFER_CREATIONFLAG_READWRITE=3;Le.BUFFER_CREATIONFLAG_UNIFORM=4;Le.BUFFER_CREATIONFLAG_VERTEX=8;Le.BUFFER_CREATIONFLAG_INDEX=16;Le.BUFFER_CREATIONFLAG_STORAGE=32;Le.BUFFER_CREATIONFLAG_INDIRECT=64;Le.RENDERPASS_MAIN=0;Le.INPUT_ALT_KEY=18;Le.INPUT_CTRL_KEY=17;Le.INPUT_META_KEY1=91;Le.INPUT_META_KEY2=92;Le.INPUT_META_KEY3=93;Le.INPUT_SHIFT_KEY=16;Le.SNAPSHOTRENDERING_STANDARD=0;Le.SNAPSHOTRENDERING_FAST=1;Le.PERSPECTIVE_CAMERA=0;Le.ORTHOGRAPHIC_CAMERA=1;Le.FOVMODE_VERTICAL_FIXED=0;Le.FOVMODE_HORIZONTAL_FIXED=1;Le.RIG_MODE_NONE=0;Le.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Le.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Le.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Le.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Le.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Le.RIG_MODE_VR=20;Le.RIG_MODE_CUSTOM=22;Le.MAX_SUPPORTED_UV_SETS=6;Le.GL_ALPHA_EQUATION_ADD=32774;Le.GL_ALPHA_EQUATION_MIN=32775;Le.GL_ALPHA_EQUATION_MAX=32776;Le.GL_ALPHA_EQUATION_SUBTRACT=32778;Le.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;Le.GL_ALPHA_FUNCTION_SRC=768;Le.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;Le.GL_ALPHA_FUNCTION_SRC_ALPHA=770;Le.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;Le.GL_ALPHA_FUNCTION_DST_ALPHA=772;Le.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;Le.GL_ALPHA_FUNCTION_DST_COLOR=774;Le.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;Le.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;Le.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;Le.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;Le.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;Le.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;Le.SnippetUrl="https://snippet.babylonjs.com";Le.FOGMODE_NONE=0;Le.FOGMODE_EXP=1;Le.FOGMODE_EXP2=2;Le.FOGMODE_LINEAR=3;Le.BYTE=5120;Le.UNSIGNED_BYTE=5121;Le.SHORT=5122;Le.UNSIGNED_SHORT=5123;Le.INT=5124;Le.UNSIGNED_INT=5125;Le.FLOAT=5126;Le.PositionKind="position";Le.NormalKind="normal";Le.TangentKind="tangent";Le.UVKind="uv";Le.UV2Kind="uv2";Le.UV3Kind="uv3";Le.UV4Kind="uv4";Le.UV5Kind="uv5";Le.UV6Kind="uv6";Le.ColorKind="color";Le.ColorInstanceKind="instanceColor";Le.MatricesIndicesKind="matricesIndices";Le.MatricesWeightsKind="matricesWeights";Le.MatricesIndicesExtraKind="matricesIndicesExtra";Le.MatricesWeightsExtraKind="matricesWeightsExtra";class Eke{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class Tke extends vt{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Eke){super(null),e.deterministicLockstep===void 0&&(e.deterministicLockstep=!1),e.timeStep!==void 0&&(this._timeStep=e.timeStep),e.lockstepMaxSteps===void 0&&(e.lockstepMaxSteps=4),this._options=e,al.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},e.renderingCanvas&&(this._renderingCanvas=e.renderingCanvas),fe.Log(`Babylon.js v${vt.Version} - Null engine`);const t=typeof self<"u"?self:typeof global<"u"?global:window;typeof URL>"u"&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Zm;return t.references=1,t}createIndexBuffer(e){const t=new Zm;return t.references=1,t}clear(e,t,i,r=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,r,n){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=e!==null&&TJ(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,r=!1,n,a,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,r){return!0}setBool(e,t){return!0}setFloat4(e,t,i,r,n){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=e!==0,t||this.setDepthWrite(e===0),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,r){}drawElementsType(e,t,i,r){}drawArraysType(e,t,i,r){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,r,n=3,a=null,o=null,l=null,c=null,u=null,h=null,d){const f=new zr(this,1),p=String(e);return f.url=p,f.generateMipMaps=!t,f.samplingMode=n,f.invertY=i,f.baseWidth=this._options.textureSize,f.baseHeight=this._options.textureSize,f.width=this._options.textureSize,f.height=this._options.textureSize,u&&(f.format=u),f.isReady=!0,a&&setTimeout(()=>{a(f)}),this._internalTexturesCache.push(f),f}_createHardwareRenderTargetWrapper(e,t,i){const r=new Mz(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};t!==void 0&&typeof t=="object"?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=t.generateDepthBuffer===void 0?!0:t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.type=t.type===void 0?0:t.type,r.samplingMode=t.samplingMode===void 0?3:t.samplingMode):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=0,r.samplingMode=3);const n=new zr(this,5),a=e.width||e,o=e.height||e;return i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,n.baseWidth=a,n.baseHeight=o,n.width=a,n.height=o,n.isReady=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,this._internalTexturesCache.push(n),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(r.type===1&&!this._caps.textureFloatLinearFiltering||r.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(r.samplingMode=1),i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer;const n=new zr(this,5);return n.baseWidth=e,n.baseHeight=e,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,this._internalTexturesCache.push(n),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,r,n,a,o,l=null,c=0,u=0,h=!1){const d=new zr(this,3);return d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=r,d.generateMipMaps=n,d.samplingMode=o,d.invertY=a,d._compression=l,d.type=c,d._useSRGBBuffer=h,this._doNotHandleContextLost||(d._bufferView=e),d}updateRawTexture(e,t,i,r,n=null,a=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=r,e._compression=n,e.type=a,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,r,n){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!n&&this.setViewport(this._cachedViewport,i,r)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Zm;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,r=!1,n){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,r){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t?(this._boundTexturesCache[this._activeChannel]=t,!0):!1}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,r,n,a=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,r=0){}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){}_uploadImageToTexture(e,t,i=0,r=0){}}Ge.prototype._partialLoadFile=function(s,e,t,i,r=null){const n=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},a=(o,l)=>{r&&o&&r(o.status+" "+o.statusText,l)};this._loadFile(s,n,void 0,void 0,!0,a)};Ge.prototype._cascadeLoadFiles=function(s,e,t,i=null){const r=[];r._internalCount=0;for(let n=0;n<6;n++)this._partialLoadFile(t[n],n,r,e,i)};Ge.prototype._cascadeLoadImgs=function(s,e,t,i,r=null,n){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,s,e,t,r,n)};Ge.prototype._partialLoadImg=function(s,e,t,i,r,n,a=null,o){const l=gh();Xw(s,h=>{t[e]=h,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&n&&n(r,t)},(h,d)=>{i&&i.removePendingData(l),a&&a(h,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};Ge.prototype.createCubeTextureBase=function(s,e,t,i,r=null,n=null,a,o=null,l=!1,c=0,u=0,h=null,d=null,f=null,p=!1,m=null){const g=h||new zr(this,7);g.isCube=!0,g.url=s,g.generateMipMaps=!i,g._lodGenerationScale=c,g._lodGenerationOffset=u,g._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),g!==h&&(g.label=s.substring(0,60)),this._doNotHandleContextLost||(g._extension=o,g._files=t,g._buffer=m);const _=s;this._transformTextureUrl&&!h&&(s=this._transformTextureUrl(s));const y=s.split("?")[0],v=y.lastIndexOf("."),x=o||(v>-1?y.substring(v).toLowerCase():""),A=bJ(x),b=(C,T)=>{s===_?n&&C&&n(C.status+" "+C.statusText,T):(fe.Warn(`Failed to load ${s}, falling back to the ${_}`),this.createCubeTextureBase(_,e,t,!!i,r,n,a,o,l,c,u,g,d,f,p,m))};if(A)A.then(C=>{const T=w=>{d&&d(g,w),C.loadCubeData(w,g,l,r,n)};m?T(m):t&&t.length===6?C.supportCascades?this._cascadeLoadFiles(e,w=>T(w.map(P=>new Uint8Array(P))),t,n):n?n("Textures type does not support cascades."):fe.Warn("Texture loader does not support cascades."):this._loadFile(s,w=>T(new Uint8Array(w)),void 0,void 0,!0,b)});else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,g,(C,T)=>{f&&f(C,T)},t,n)}return this._internalTexturesCache.push(g),g};class Mke{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Li.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Li.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}Ge.prototype.getGPUFrameTimeCounter=function(){return null};Ge.prototype.captureGPUFrameTime=function(s){};Ge.prototype.createQuery=function(){return null};Ge.prototype.deleteQuery=function(s){return this};Ge.prototype.isQueryResultAvailable=function(s){return!1};Ge.prototype.getQueryResult=function(s){return 0};Ge.prototype.beginOcclusionQuery=function(s,e){return!1};Ge.prototype.endOcclusionQuery=function(s){return this};Object.defineProperty(Li.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(s){this._occlusionDataStorage.isOcclusionQueryInProgress=s},enumerable:!1,configurable:!0});Object.defineProperty(Li.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Mke),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(Li.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(s){this._occlusionDataStorage.isOccluded=s},enumerable:!0,configurable:!0});Object.defineProperty(Li.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(s){this._occlusionDataStorage.occlusionQueryAlgorithmType=s},enumerable:!0,configurable:!0});Object.defineProperty(Li.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(s){this._occlusionDataStorage.occlusionType=s},enumerable:!0,configurable:!0});Object.defineProperty(Li.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(s){this._occlusionDataStorage.occlusionRetryCount=s},enumerable:!0,configurable:!0});Object.defineProperty(Li.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(s){this._occlusionDataStorage.forceRenderingWhenOccluded=s},enumerable:!0,configurable:!0});Li.prototype._checkOcclusionQuery=function(){const s=this._occlusionDataStorage;if(s.occlusionType===Li.OCCLUSION_TYPE_NONE)return s.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return s.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const r=e.getQueryResult(this._occlusionQuery);s.isOcclusionQueryInProgress=!1,s.occlusionInternalRetryCounter=0,s.isOccluded=!(r>0)}else if(s.occlusionInternalRetryCounter++,s.occlusionRetryCount!==-1&&s.occlusionInternalRetryCounter>s.occlusionRetryCount)s.isOcclusionQueryInProgress=!1,s.occlusionInternalRetryCounter=0,s.isOccluded=s.occlusionType===Li.OCCLUSION_TYPE_OPTIMISTIC?!1:s.isOccluded;else return s.occlusionType===Li.OCCLUSION_TYPE_OPTIMISTIC?!1:s.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),this._occlusionQuery&&e.beginOcclusionQuery(s.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(s.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return s.isOccluded};class d3t{}const Rke=new Ae,Ike=new Ae;Object.defineProperty(Ge.prototype,"onBeforeViewRenderObservable",{get:function(){return Rke}});Object.defineProperty(Ge.prototype,"onAfterViewRenderObservable",{get:function(){return Ike}});Object.defineProperty(Ge.prototype,"inputElement",{get:function(){return this._inputElement},set:function(s){var e;this._inputElement!==s&&(this._inputElement=s,(e=this._onEngineViewChanged)==null||e.call(this))}});Ge.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()};Ge.prototype.registerView=function(s,e,t){this.views||(this.views=[]);for(const n of this.views)if(n.target===s)return n;const i=this.getRenderingCanvas();i&&(s.width=i.width,s.height=i.height);const r={target:s,camera:e,clearBeforeCopy:t,enabled:!0,id:(Math.random()*1e5).toFixed()};return this.views.push(r),e&&!Array.isArray(e)&&e.onDisposeObservable.add(()=>{this.unRegisterView(s)}),r};Ge.prototype.unRegisterView=function(s){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===s){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};Ge.prototype._renderViewStep=function(s){const e=s.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();Rke.notifyObservers(s);const r=s.camera;let n=null,a=null,o=null;if(r&&(o=Array.isArray(r)?r[0].getScene():r.getScene(),n=o.activeCamera,a=o.activeCameras,Array.isArray(r)?o.activeCameras=r:(o.activeCamera=r,o.activeCameras=null)),this.activeView=s,s.customResize)s.customResize(e);else{const l=Math.floor(e.clientWidth/this._hardwareScalingLevel),c=Math.floor(e.clientHeight/this._hardwareScalingLevel),u=l!==e.width||i.width!==e.width||c!==e.height||i.height!==e.height;e.clientWidth&&e.clientHeight&&u&&(e.width=l,e.height=c,this.setSize(l,c))}return!i.width||!i.height?!1:(this._renderFrame(),this.flushFramebuffer(),s.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),o&&(o.activeCameras=a,o.activeCamera=n),Ike.notifyObservers(s),!0)};Ge.prototype._renderViews=function(){if(!this.views||this.views.length===0||!this.getRenderingCanvas())return!1;let e;for(const t of this.views){if(!t.enabled)continue;if(t.target===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return e&&!this._renderViewStep(e)?!1:(this.activeView=null,!0)};Ge.prototype._debugPushGroup=function(s,e){};Ge.prototype._debugPopGroup=function(s){};Ge.prototype._debugInsertMarker=function(s,e){};Ge.prototype._debugFlushPendingCommands=function(){};class Pke{constructor(){this._timeElapsedQueryEnded=!1}}vt.prototype.createQuery=function(){const s=this._gl.createQuery();if(!s)throw new Error("Unable to create Occlusion Query");return s};vt.prototype.deleteQuery=function(s){return this._gl.deleteQuery(s),this};vt.prototype.isQueryResultAvailable=function(s){return this._gl.getQueryParameter(s,this._gl.QUERY_RESULT_AVAILABLE)};vt.prototype.getQueryResult=function(s){return this._gl.getQueryParameter(s,this._gl.QUERY_RESULT)};vt.prototype.beginOcclusionQuery=function(s,e){const t=this._getGlAlgorithmType(s);return this._gl.beginQuery(t,e),!0};vt.prototype.endOcclusionQuery=function(s){const e=this._getGlAlgorithmType(s);return this._gl.endQuery(e),this};vt.prototype._createTimeQuery=function(){const s=this.getCaps().timerQuery;return s.createQueryEXT?s.createQueryEXT():this.createQuery()};vt.prototype._deleteTimeQuery=function(s){const e=this.getCaps().timerQuery;if(e.deleteQueryEXT){e.deleteQueryEXT(s);return}this.deleteQuery(s)};vt.prototype._getTimeQueryResult=function(s){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(s,e.QUERY_RESULT_EXT):this.getQueryResult(s)};vt.prototype._getTimeQueryAvailability=function(s){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(s,e.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(s)};vt.prototype.startTimeQuery=function(){const s=this.getCaps(),e=s.timerQuery;if(!e)return null;const t=new Pke;if(this._gl.getParameter(e.GPU_DISJOINT_EXT),s.canUseTimestampForTimerQuery)t._startTimeQuery=this._createTimeQuery(),t._startTimeQuery&&e.queryCounterEXT(t._startTimeQuery,e.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;t._timeElapsedQuery=this._createTimeQuery(),t._timeElapsedQuery&&(e.beginQueryEXT?e.beginQueryEXT(e.TIME_ELAPSED_EXT,t._timeElapsedQuery):this._gl.beginQuery(e.TIME_ELAPSED_EXT,t._timeElapsedQuery)),this._currentNonTimestampToken=t}return t};vt.prototype.endTimeQuery=function(s){const e=this.getCaps(),t=e.timerQuery;if(!t||!s)return-1;if(e.canUseTimestampForTimerQuery){if(!s._startTimeQuery)return-1;s._endTimeQuery||(s._endTimeQuery=this._createTimeQuery(),s._endTimeQuery&&t.queryCounterEXT(s._endTimeQuery,t.TIMESTAMP_EXT))}else if(!s._timeElapsedQueryEnded){if(!s._timeElapsedQuery)return-1;t.endQueryEXT?t.endQueryEXT(t.TIME_ELAPSED_EXT):(this._gl.endQuery(t.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),s._timeElapsedQueryEnded=!0}const i=this._gl.getParameter(t.GPU_DISJOINT_EXT);let r=!1;if(s._endTimeQuery?r=this._getTimeQueryAvailability(s._endTimeQuery):s._timeElapsedQuery&&(r=this._getTimeQueryAvailability(s._timeElapsedQuery)),r&&!i){let n=0;if(e.canUseTimestampForTimerQuery){if(!s._startTimeQuery||!s._endTimeQuery)return-1;const a=this._getTimeQueryResult(s._startTimeQuery);n=this._getTimeQueryResult(s._endTimeQuery)-a,this._deleteTimeQuery(s._startTimeQuery),this._deleteTimeQuery(s._endTimeQuery),s._startTimeQuery=null,s._endTimeQuery=null}else{if(!s._timeElapsedQuery)return-1;n=this._getTimeQueryResult(s._timeElapsedQuery),this._deleteTimeQuery(s._timeElapsedQuery),s._timeElapsedQuery=null,s._timeElapsedQueryEnded=!1}return n}return-1};vt.prototype._captureGPUFrameTime=!1;vt.prototype._gpuFrameTime=new io;vt.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};vt.prototype.captureGPUFrameTime=function(s){s!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=s,s?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))};vt.prototype._getGlAlgorithmType=function(s){return s===Li.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var f3t=!0;vt.prototype.createTransformFeedback=function(){const s=this._gl.createTransformFeedback();if(!s)throw new Error("Unable to create Transform Feedback");return s};vt.prototype.deleteTransformFeedback=function(s){this._gl.deleteTransformFeedback(s)};vt.prototype.bindTransformFeedback=function(s){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,s)};vt.prototype.beginTransformFeedback=function(s=!0){this._gl.beginTransformFeedback(s?this._gl.POINTS:this._gl.TRIANGLES)};vt.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};vt.prototype.setTranformFeedbackVaryings=function(s,e){this._gl.transformFeedbackVaryings(s,e,this._gl.INTERLEAVED_ATTRIBS)};vt.prototype.bindTransformFeedbackBuffer=function(s){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,s?s.underlyingResource:null)};vt.prototype.readTransformFeedbackBuffer=function(s){this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,s)};bi.prototype.updateVideoTexture=function(s,e,t){if(!s||s._isDisabled)return;const i=this._getInternalFormat(s.format),r=this._getRGBABufferInternalSizedFormat(0,s.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,s,!0);this._unpackFlipY(!t);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,i,this._gl.UNSIGNED_BYTE,e),this._gl.getError()!==0?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,i,this._gl.UNSIGNED_BYTE,e);else{if(!s._workingCanvas){s._workingCanvas=this.createCanvas(s.width,s.height);const a=s._workingCanvas.getContext("2d");if(!a)throw new Error("Unable to get 2d context");s._workingContext=a,s._workingCanvas.width=s.width,s._workingCanvas.height=s.height}s._workingContext.clearRect(0,0,s.width,s.height),s._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,s.width,s.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,i,this._gl.UNSIGNED_BYTE,s._workingCanvas)}s.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),s.isReady=!0}catch{s._isDisabled=!0}};bi.prototype.restoreSingleAttachment=function(){const s=this._gl;this.bindAttachments([s.BACK])};bi.prototype.restoreSingleAttachmentForRenderTarget=function(){const s=this._gl;this.bindAttachments([s.COLOR_ATTACHMENT0])};bi.prototype.buildTextureLayout=function(s){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],i.readBuffer(r[a]),i.drawBuffers(r),i.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let a=0;a1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];i.drawBuffers(r)}for(let a=0;a1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),b.label=(e==null?void 0:e.label)??"MultiRenderTargetWrapper";const C=this._gl,T=C.createFramebuffer();this._bindUnboundFramebuffer(T);const w=s.width||s,P=s.height||s,M=[],R=[],I=this.webGLVersion>1&&a&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),L=this._setupFramebufferDepthAttachments(!I&&n,!a&&r,w,P);b._framebuffer=T,b._depthStencilBuffer=L,b._generateDepthBuffer=!a&&r,b._generateStencilBuffer=!I&&n,b._attachments=R;for(let k=0;k1||this.isWebGPU);const Z=this.webGLVersion>1,q=C[Z?"COLOR_ATTACHMENT"+k:"COLOR_ATTACHMENT"+k+"_WEBGL"];if(R.push(q),K===-1)continue;const ie=new zr(this,6);M[k]=ie,C.activeTexture(C["TEXTURE"+k]),C.bindTexture(K,ie._hardwareTexture.underlyingResource),C.texParameteri(K,C.TEXTURE_MAG_FILTER,W.mag),C.texParameteri(K,C.TEXTURE_MIN_FILTER,W.min),C.texParameteri(K,C.TEXTURE_WRAP_S,C.CLAMP_TO_EDGE),C.texParameteri(K,C.TEXTURE_WRAP_T,C.CLAMP_TO_EDGE);const ae=this._getRGBABufferInternalSizedFormat(H,z,j),ue=this._getInternalFormat(z),ce=this._getWebGLTextureType(H);if(Z&&(K===35866||K===32879))K===35866?ie.is2DArray=!0:ie.is3D=!0,ie.baseDepth=ie.depth=U,C.texImage3D(K,0,ae,w,P,U,0,ue,ce,null);else if(K===34067){for(let N=0;N<6;N++)C.texImage2D(C.TEXTURE_CUBE_MAP_POSITIVE_X+N,0,ae,w,P,0,ue,ce,null);ie.isCube=!0}else C.texImage2D(C.TEXTURE_2D,0,ae,w,P,0,ue,ce,null);i&&C.generateMipmap(K),this._bindTextureDirectly(K,null),ie.baseWidth=w,ie.baseHeight=P,ie.width=w,ie.height=P,ie.isReady=!0,ie.samples=1,ie.generateMipMaps=i,ie.samplingMode=V,ie.type=H,ie._useSRGBBuffer=j,ie.format=z,this._internalTexturesCache.push(ie)}if(a&&this._caps.depthTextureExtension){const k=new zr(this,14);let V=5,H=C.DEPTH_COMPONENT16,j=C.DEPTH_COMPONENT,z=C.UNSIGNED_SHORT,K=C.DEPTH_ATTACHMENT;this.webGLVersion<2?H=C.DEPTH_COMPONENT:o===14?(V=1,z=C.FLOAT,H=C.DEPTH_COMPONENT32F):o===18?(V=0,z=C.FLOAT_32_UNSIGNED_INT_24_8_REV,H=C.DEPTH32F_STENCIL8,j=C.DEPTH_STENCIL,K=C.DEPTH_STENCIL_ATTACHMENT):o===16?(V=0,z=C.UNSIGNED_INT,H=C.DEPTH_COMPONENT24,K=C.DEPTH_ATTACHMENT):(o===13||o===17)&&(V=12,z=C.UNSIGNED_INT_24_8,H=C.DEPTH24_STENCIL8,j=C.DEPTH_STENCIL,K=C.DEPTH_STENCIL_ATTACHMENT),C.activeTexture(C.TEXTURE0),C.bindTexture(C.TEXTURE_2D,k._hardwareTexture.underlyingResource),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MAG_FILTER,C.NEAREST),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MIN_FILTER,C.NEAREST),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_S,C.CLAMP_TO_EDGE),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_T,C.CLAMP_TO_EDGE),C.texImage2D(C.TEXTURE_2D,0,H,w,P,0,j,z,null),C.framebufferTexture2D(C.FRAMEBUFFER,K,C.TEXTURE_2D,k._hardwareTexture.underlyingResource,0),k.baseWidth=w,k.baseHeight=P,k.width=w,k.height=P,k.isReady=!0,k.samples=1,k.generateMipMaps=i,k.samplingMode=1,k.format=o,k.type=V,M[l]=k,this._internalTexturesCache.push(k)}return b.setTextures(M),t&&C.drawBuffers(R),this._bindUnboundFramebuffer(null),b.setLayerAndFaceIndices(x,v),this.resetTextureCache(),b};bi.prototype.updateMultipleRenderTargetTextureSampleCount=function(s,e,t=!0){if(this.webGLVersion<2||!s||!s.texture)return 1;if(s.samples===e)return e;const i=s._attachments.length;if(i===0)return 1;const r=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const n=!!s._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(s._depthStencilBuffer),s._depthStencilBuffer=null),s._MSAAFramebuffer&&(r.deleteFramebuffer(s._MSAAFramebuffer),s._MSAAFramebuffer=null),e>1&&typeof r.renderbufferStorageMultisample=="function"){const a=r.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");s._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);const o=[];for(let l=0;l1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],d=this._createRenderBuffer(c.width,c.height,e,-1,this._getRGBABufferInternalSizedFormat(c.type,c.format,c._useSRGBBuffer),h);if(!d)throw new Error("Unable to create multi sampled framebuffer");u.addMSAARenderBuffer(d),c.samples=e,o.push(h)}t&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(s._framebuffer);return n&&(s._depthStencilBuffer=this._setupFramebufferDepthAttachments(s._generateStencilBuffer,s._generateDepthBuffer,s.texture.width,s.texture.height,e)),this._bindUnboundFramebuffer(null),e};bi.prototype._createDepthStencilCubeTexture=function(s,e){const t=new zr(this,12);if(t.isCube=!0,this.webGLVersion===1)return fe.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,s,i.generateStencil,i.bilinearFiltering,i.comparisonFunction);for(let n=0;n<6;n++)i.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH24_STENCIL8,s,s,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH_COMPONENT24,s,s,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};bi.prototype._setCubeMapTextureParams=function(s,e,t){const i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),s.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),s._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};bi.prototype.createCubeTexture=function(s,e,t,i,r=null,n=null,a,o=null,l=!1,c=0,u=0,h=null,d,f=!1,p=null){const m=this._gl;return this.createCubeTextureBase(s,e,t,!!i,r,n,a,o,l,c,u,h,g=>this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,g,!0),(g,_)=>{const y=this.needPOTTextures?ad(_[0].width,this._caps.maxCubemapTextureSize):_[0].width,v=y,x=[m.TEXTURE_CUBE_MAP_POSITIVE_X,m.TEXTURE_CUBE_MAP_POSITIVE_Y,m.TEXTURE_CUBE_MAP_POSITIVE_Z,m.TEXTURE_CUBE_MAP_NEGATIVE_X,m.TEXTURE_CUBE_MAP_NEGATIVE_Y,m.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,g,!0),this._unpackFlipY(!1);const A=a?this._getInternalFormat(a,g._useSRGBBuffer):g._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:m.RGBA;let b=a?this._getInternalFormat(a):m.RGBA;g._useSRGBBuffer&&this.webGLVersion===1&&(b=A);for(let C=0;C1,s=>s.y,s=>s.z,s=>s.x,s=>s.x*s.y,s=>s.y*s.z,s=>3*s.z*s.z-1,s=>s.x*s.z,s=>s.x*s.x-s.y*s.y],k2=(s,e)=>g1[s]*p3t[s](e),U2=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class bx{constructor(){this.preScaled=!1,this.l00=D.Zero(),this.l1_1=D.Zero(),this.l10=D.Zero(),this.l11=D.Zero(),this.l2_2=D.Zero(),this.l2_1=D.Zero(),this.l20=D.Zero(),this.l21=D.Zero(),this.l22=D.Zero()}addLight(e,t,i){se.Vector3[0].set(t.r,t.g,t.b);const r=se.Vector3[0],n=se.Vector3[1];r.scaleToRef(i,n),n.scaleToRef(k2(0,e),se.Vector3[2]),this.l00.addInPlace(se.Vector3[2]),n.scaleToRef(k2(1,e),se.Vector3[2]),this.l1_1.addInPlace(se.Vector3[2]),n.scaleToRef(k2(2,e),se.Vector3[2]),this.l10.addInPlace(se.Vector3[2]),n.scaleToRef(k2(3,e),se.Vector3[2]),this.l11.addInPlace(se.Vector3[2]),n.scaleToRef(k2(4,e),se.Vector3[2]),this.l2_2.addInPlace(se.Vector3[2]),n.scaleToRef(k2(5,e),se.Vector3[2]),this.l2_1.addInPlace(se.Vector3[2]),n.scaleToRef(k2(6,e),se.Vector3[2]),this.l20.addInPlace(se.Vector3[2]),n.scaleToRef(k2(7,e),se.Vector3[2]),this.l21.addInPlace(se.Vector3[2]),n.scaleToRef(k2(8,e),se.Vector3[2]),this.l22.addInPlace(se.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(U2[0]),this.l1_1.scaleInPlace(U2[1]),this.l10.scaleInPlace(U2[2]),this.l11.scaleInPlace(U2[3]),this.l2_2.scaleInPlace(U2[4]),this.l2_1.scaleInPlace(U2[5]),this.l20.scaleInPlace(U2[6]),this.l21.scaleInPlace(U2[7]),this.l22.scaleInPlace(U2[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(g1[0]),this.l1_1.scaleInPlace(g1[1]),this.l10.scaleInPlace(g1[2]),this.l11.scaleInPlace(g1[3]),this.l2_2.scaleInPlace(g1[4]),this.l2_1.scaleInPlace(g1[5]),this.l20.scaleInPlace(g1[6]),this.l21.scaleInPlace(g1[7]),this.l22.scaleInPlace(g1[8])}updateFromArray(e){return D.FromArrayToRef(e[0],0,this.l00),D.FromArrayToRef(e[1],0,this.l1_1),D.FromArrayToRef(e[2],0,this.l10),D.FromArrayToRef(e[3],0,this.l11),D.FromArrayToRef(e[4],0,this.l2_2),D.FromArrayToRef(e[5],0,this.l2_1),D.FromArrayToRef(e[6],0,this.l20),D.FromArrayToRef(e[7],0,this.l21),D.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return D.FromFloatsToRef(e[0],e[1],e[2],this.l00),D.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),D.FromFloatsToRef(e[6],e[7],e[8],this.l10),D.FromFloatsToRef(e[9],e[10],e[11],this.l11),D.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),D.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),D.FromFloatsToRef(e[18],e[19],e[20],this.l20),D.FromFloatsToRef(e[21],e[22],e[23],this.l21),D.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new bx().updateFromArray(e)}static FromPolynomial(e){const t=new bx;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class hg{constructor(){this.x=D.Zero(),this.y=D.Zero(),this.z=D.Zero(),this.xx=D.Zero(),this.yy=D.Zero(),this.zz=D.Zero(),this.xy=D.Zero(),this.yz=D.Zero(),this.zx=D.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=bx.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){se.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=se.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),se.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),se.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(se.Vector3[0]).addInPlace(se.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(se.Vector3[0]).subtractInPlace(se.Vector3[1]),this.zz.copyFrom(e.l00),se.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(se.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new hg().updateFromHarmonics(e)}static FromArray(e){const t=new hg;return D.FromArrayToRef(e[0],0,t.x),D.FromArrayToRef(e[1],0,t.y),D.FromArrayToRef(e[2],0,t.z),D.FromArrayToRef(e[3],0,t.xx),D.FromArrayToRef(e[4],0,t.yy),D.FromArrayToRef(e[5],0,t.zz),D.FromArrayToRef(e[6],0,t.yz),D.FromArrayToRef(e[7],0,t.zx),D.FromArrayToRef(e[8],0,t.xy),t}}class FI{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class oT{static ConvertCubeMapTextureToSphericalPolynomial(e){var d;if(!e.isCube)return null;(d=e.getScene())==null||d.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let n,a;e.isRenderTarget?(n=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(n=e.readPixels(2,void 0,void 0,!1),a=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),c=e.gammaSpace,u=5;let h=0;return(e.textureType==1||e.textureType==2)&&(h=1),new Promise(f=>{Promise.all([r,i,n,a,o,l]).then(([p,m,g,_,y,v])=>{const x={size:t,right:m,left:p,up:g,down:_,front:y,back:v,format:u,type:h,gammaSpace:c};f(this.ConvertCubeMapToSphericalPolynomial(x))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new bx;let i=0;const r=2/e.size,n=r,a=.5*r,o=a-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],p=e[f.name];let m=o;const g=e.format===5?4:3;for(let _=0;_w){const R=w/M;b*=R,C*=R,T*=R}}else b=At.Clamp(b,0,w),C=At.Clamp(C,0,w),T=At.Clamp(T,0,w);const P=new Re(b,C,T);t.addLight(x,P,A),i+=A,y+=r}m+=n}}const h=4*Math.PI*6/6/i;return t.scaleInPlace(h),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),hg.FromHarmonics(t)}}oT._FileFaces=[new FI("right",new D(1,0,0),new D(0,0,-1),new D(0,-1,0)),new FI("left",new D(-1,0,0),new D(0,0,1),new D(0,-1,0)),new FI("up",new D(0,1,0),new D(1,0,0),new D(0,0,1)),new FI("down",new D(0,-1,0),new D(1,0,0),new D(0,0,-1)),new FI("front",new D(0,0,1),new D(1,0,0),new D(0,-1,0)),new FI("back",new D(0,0,-1),new D(-1,0,0),new D(0,-1,0))];oT.MAX_HDRI_VALUE=4096;oT.PRESERVE_CLAMPED_COLORS=!1;const m3t="lodPixelShader",g3t=`#extension GL_EXT_shader_texture_lod : enable precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void) {gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}} `;de.ShadersStore[m3t]=g3t;const _3t="lodCubePixelShader",v3t=`precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void) {vec2 uv=vUV*2.0-1.0; #ifdef POSITIVEX gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod); #endif #ifdef NEGATIVEX gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod); #endif #ifdef POSITIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod); #endif #ifdef NEGATIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod); #endif #ifdef POSITIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod); #endif #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod); #endif if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}} `;de.ShadersStore[_3t]=v3t;function wke(s,e,t,i=!0){const r=s.getScene(),n=r.getEngine(),a=new Rs("resized"+s.name,{width:e,height:t},r,!s.noMipmap,!0,s._texture.type,!1,s.samplingMode,!1);a.wrapU=s.wrapU,a.wrapV=s.wrapV,a.uOffset=s.uOffset,a.vOffset=s.vOffset,a.uScale=s.uScale,a.vScale=s.vScale,a.uAng=s.uAng,a.vAng=s.vAng,a.wAng=s.wAng,a.coordinatesIndex=s.coordinatesIndex,a.level=s.level,a.anisotropicFilteringLevel=s.anisotropicFilteringLevel,a._texture.isReady=!1,s.wrapU=xe.CLAMP_ADDRESSMODE,s.wrapV=xe.CLAMP_ADDRESSMODE;const o=new D0("pass",1,null,i?xe.BILINEAR_SAMPLINGMODE:xe.NEAREST_SAMPLINGMODE,n,!1,0);return o.externalTextureSamplerBinding=!0,o.onEffectCreatedObservable.addOnce(l=>{l.executeWhenCompiled(()=>{o.onApply=function(u){u.setTexture("textureSampler",s)};const c=a.renderTarget;c&&(r.postProcessManager.directRender([o],c),n.unBindFramebuffer(c),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)})}),a}function aee(s,e,t,i,r,n,a,o){const l=e.getEngine();return e.isReady=!1,r=r??e.samplingMode,i=i??e.type,n=n??e.format,a=a??e.width,o=o??e.height,i===-1&&(i=0),new Promise(c=>{const u=new Ft("postprocess",s,null,null,1,null,r,l,!1,void 0,i,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;const h=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:i,format:n});u.onEffectCreatedObservable.addOnce(d=>{d.executeWhenCompiled(()=>{u.onApply=f=>{f._bindTexture("textureSampler",e),f.setFloat2("scale",1,1)},t.postProcessManager.directRender([u],h,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),u&&u.dispose(),h._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,c(e)})})})}let oY,MTe;function Fm(s){oY||(oY=new Float32Array(1),MTe=new Int32Array(oY.buffer)),oY[0]=s;const e=MTe[0];let t=e>>16&32768,i=e>>12&2047;const r=e>>23&255;return r<103?t:r>142?(t|=31744,t|=(r==255?0:1)&&e&8388607,t):r<113?(i|=2048,t|=(i>>114-r)+(i>>113-r&1),t):(t|=r-112<<10|i>>1,t+=i&1,t)}function Im(s){const e=(s&32768)>>15,t=(s&31744)>>10,i=s&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}const y3t=async(s,e,t,i,r)=>{const n=s.getScene(),a=n.getEngine();let o;if(!s.isCube)o=new Ft("lod","lod",["lod","gamma"],null,1,null,xe.NEAREST_NEAREST_MIPNEAREST,a);else{const u=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];o=new Ft("lodCube","lodCube",["lod","gamma"],null,1,null,xe.NEAREST_NEAREST_MIPNEAREST,a,!1,u[i])}await new Promise(u=>{o.onEffectCreatedObservable.addOnce(h=>{h.executeWhenCompiled(()=>{u(0)})})});const l=new Rs("temp",{width:e,height:t},n,!1);o.onApply=function(u){u.setTexture("textureSampler",s),u.setFloat("lod",r),u.setBool("gamma",s.gammaSpace)};const c=s.getInternalTexture();try{if(l.renderTarget&&c){const u=c.samplingMode;r!==0?s.updateSamplingMode(xe.NEAREST_NEAREST_MIPNEAREST):s.updateSamplingMode(xe.NEAREST_NEAREST),n.postProcessManager.directRender([o],l.renderTarget,!0),s.updateSamplingMode(u);const h=await a.readPixels(0,0,e,t),d=new Uint8Array(h.buffer,0,h.byteLength);return a.unBindFramebuffer(l.renderTarget),d}else throw Error("Render to texture failed.")}finally{l.dispose(),o.dispose()}};async function Dke(s,e,t,i=0,r=0){return!s.isReady()&&s._texture&&await new Promise((n,a)=>{if(s._texture===null){a(0);return}s._texture.onLoadedObservable.addOnce(()=>{n(0)})}),await y3t(s,e,t,i,r)}const Lke={CreateResizedCopy:wke,ApplyPostProcess:aee,ToHalfFloat:Fm,FromHalfFloat:Im,GetTextureDataAsync:Dke},x3t=542327876,RTe=131072,ITe=512,PTe=4,wTe=64,DTe=131072;function oee(s){return s.charCodeAt(0)+(s.charCodeAt(1)<<8)+(s.charCodeAt(2)<<16)+(s.charCodeAt(3)<<24)}function A3t(s){return String.fromCharCode(s&255,s>>8&255,s>>16&255,s>>24&255)}const LTe=oee("DXT1"),OTe=oee("DXT3"),NTe=oee("DXT5"),Dne=oee("DX10"),FTe=113,BTe=116,kTe=2,UTe=10,b3t=88,Lne=31,C3t=0,S3t=1,zTe=2,VTe=3,One=4,GTe=7,Nne=20,WTe=21,E3t=22,T3t=23,M3t=24,R3t=25,I3t=26,P3t=28,w3t=32;class Ks{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,Lne),i=new Int32Array(e.buffer,e.byteOffset,Lne+4);let r=1;t[zTe]&RTe&&(r=Math.max(1,t[GTe]));const n=t[WTe],a=n===Dne?i[w3t]:0;let o=0;switch(n){case FTe:o=2;break;case BTe:o=1;break;case Dne:if(a===UTe){o=2;break}if(a===kTe){o=1;break}}return{width:t[One],height:t[VTe],mipmapCount:r,isFourCC:(t[Nne]&PTe)===PTe,isRGB:(t[Nne]&wTe)===wTe,isLuminance:(t[Nne]&DTe)===DTe,isCube:(t[P3t]&ITe)===ITe,isCompressed:n===LTe||n===OTe||n===NTe,dxgiFormat:a,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,n,a){const o=new Float32Array(r),l=new Uint16Array(n,i);let c=0;for(let u=0;u>8)}static _GetRGBArrayBuffer(e,t,i,r,n,a,o,l){const c=new Uint8Array(r),u=new Uint8Array(n,i);let h=0;for(let d=0;d0?r.sphericalPolynomial=oT.ConvertCubeMapToSphericalPolynomial({size:d[One],right:u[0],left:u[1],up:u[2],down:u[3],front:u[4],back:u[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}Ks.StoreLODInAlphaChannel=!1;bi.prototype.createPrefilteredCubeTexture=function(s,e,t,i,r=null,n=null,a,o=null,l=!0){const c=u=>{if(!u){r&&r(null);return}const h=u.texture;if(l?u.info.sphericalPolynomial&&(h._sphericalPolynomial=u.info.sphericalPolynomial):h._sphericalPolynomial=new hg,h._source=9,this.getCaps().textureLOD){r&&r(h);return}const d=3,f=this._gl,p=u.width;if(!p)return;const m=[];for(let g=0;g{const a="\\b"+n+"\\b";return s&&(s===n||s.match(new RegExp(a,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return s;const t=s.lastIndexOf("."),i=s.lastIndexOf("?"),r=i>-1?s.substring(i,s.length):"";return(t>-1?s.substring(0,t):s)+this._textureFormatInUse+r}Object.defineProperty(vt.prototype,"texturesSupported",{get:function(){const s=[];return this._caps.astc&&s.push("-astc.ktx"),this._caps.s3tc&&s.push("-dxt.ktx"),this._caps.pvrtc&&s.push("-pvrtc.ktx"),this._caps.etc2&&s.push("-etc2.ktx"),this._caps.etc1&&s.push("-etc1.ktx"),s},enumerable:!0,configurable:!0});Object.defineProperty(vt.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});vt.prototype.setCompressedTextureExclusions=function(s){this._excludedCompressedTextures=s};vt.prototype.setTextureFormatToUse=function(s){const e=this.texturesSupported;for(let t=0,i=e.length;t{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}Cx.DEFAULT_BUFFER_SIZE=65536;class zk{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),r=i.getCaps(),n=t.isReady;let a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=async()=>{const l=i.isWebGPU,c=l?1:0;t.isReady=!1,this._ShaderImported||(this._ShaderImported=!0,l?await Promise.all([Ue(()=>Promise.resolve().then(()=>cet),void 0),Ue(()=>Promise.resolve().then(()=>yPt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>tet),void 0),Ue(()=>Promise.resolve().then(()=>vPt),void 0)]));const u=new Ft("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1,void 0,c);u.externalTextureSamplerBinding=!0;const h=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});u.onEffectCreatedObservable.addOnce(d=>{d.executeWhenCompiled(()=>{u.onApply=f=>{f._bindTexture("textureSampler",t),f.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([u],h,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),u&&u.dispose(),h._swapAndDie(t),t.isReady=!0})})};a&&(n?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return aee("rgbdEncode",e,t,i,1,5)}}zk._ShaderImported=!1;$r.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty($r.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=oT.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(s=>{this._texture._sphericalPolynomial=s,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(s){this._texture&&(this._texture._sphericalPolynomial=s)},enumerable:!0,configurable:!0});const p1e="image/png",Que=2,KB=[134,22,135,150,246,214,150,54];function lee(s){const e=new DataView(s.buffer,s.byteOffset,s.byteLength);let t=0;for(let a=0;aQue)throw new Error(`Unsupported babylon environment map version "${s.version}". Latest supported version is "${Que}".`);return s.version===2||(s={...s,version:2,imageType:p1e}),s}async function Oke(s,e={}){var A;const t=s.getInternalTexture();if(!t)return Promise.reject("The cube texture is invalid.");const i=e.imageType??p1e,r=t.getEngine();if(s.textureType!==2&&s.textureType!==1&&s.textureType!==0&&s.textureType!==0&&s.textureType!==7&&s.textureType!==-1)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let n=1;if(!r.getCaps().textureFloatRender&&(n=2,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");s.sphericalPolynomial;const a=(A=s.getInternalTexture())==null?void 0:A._sphericalPolynomialPromise,o=t.width,l=new gt(r),c={};r.flushFramebuffer();const u=At.ILog2(t.width);for(let b=0;b<=u;b++){const C=Math.pow(2,u-b);for(let T=0;T<6;T++){let w=await s.readPixels(T,b,void 0,!1);if(w&&w.byteLength===w.length){const I=new Float32Array(w.byteLength*4);for(let L=0;L{if(t){const f=e.createTexture(null,!0,!0,null,1,null,p=>{d(p)},s);i==null||i.onEffectCreatedObservable.addOnce(p=>{p.executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=m=>{m._bindTexture("textureSampler",f),m.setFloat2("scale",1,e._features.needsInvertingBitmap&&s instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],c,!0,n,a),e.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(r),h())})})}else{if(e._uploadImageToTexture(u,s,n,a),o){const f=l[a];f&&e._uploadImageToTexture(f._texture,s,n,0)}h()}})}async function Vk(s,e,t=p1e){if(!Me.IsExponentOfTwo(s.width))throw new Error("Texture size must be a power of two");const i=At.ILog2(s.width)+1,r=s.getEngine();let n=!1,a=!1,o=null,l=null,c=null;const u=r.getCaps();s.format=5,s.type=0,s.generateMipMaps=!0,s._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,s),u.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,s.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,s.type=1):n=!1:(n=!1,a=!0,c={});let h=0;if(n)r.isWebGPU?(h=1,await Ue(()=>Promise.resolve().then(()=>cet),void 0)):await Ue(()=>Promise.resolve().then(()=>tet),void 0),o=new Ft("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,s.type,void 0,null,!1,void 0,h),s._isRGBD=!1,s.invertY=!1,l=r.createRenderTargetCubeTexture(s.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:s.type,format:5});else if(s._isRGBD=!0,s.invertY=!0,a){const p=s._lodGenerationScale,m=s._lodGenerationOffset;for(let g=0;g<3;g++){const y=1-g/2,v=m,x=(i-1)*p+m,A=v+(x-v)*y,b=Math.round(Math.min(Math.max(A,0),x)),C=new zr(r,2);C.isCube=!0,C.invertY=!0,C.generateMipMaps=!1,r.updateTextureSamplingMode(2,C);const T=new $r(null);switch(T._isCube=!0,T._texture=C,c[b]=T,g){case 0:s._lodTextureLow=T;break;case 1:s._lodTextureMid=T;break;case 2:s._lodTextureHigh=T;break}}}const d=[];for(let f=0;fKTe(v,r,n,o,_,p,f,a,c,l,s));else{const v=new Image;v.src=_,y=new Promise((x,A)=>{v.onload=()=>{KTe(v,r,n,o,_,p,f,a,c,l,s).then(()=>x()).catch(b=>{A(b)})},v.onerror=b=>{A(b)}})}d.push(y)}if(e.length{l&&(r._releaseTexture(s),l._swapAndDie(s)),o&&o.dispose(),a&&(s._lodTextureHigh&&s._lodTextureHigh._texture&&(s._lodTextureHigh._texture.isReady=!0),s._lodTextureMid&&s._lodTextureMid._texture&&(s._lodTextureMid._texture.isReady=!0),s._lodTextureLow&&s._lodTextureLow._texture&&(s._lodTextureLow._texture.isReady=!0))})}function uee(s,e){e=Gz(e);const t=e.irradiance;if(!t)return;const i=new hg;D.FromArrayToRef(t.x,0,i.x),D.FromArrayToRef(t.y,0,i.y),D.FromArrayToRef(t.z,0,i.z),D.FromArrayToRef(t.xx,0,i.xx),D.FromArrayToRef(t.yy,0,i.yy),D.FromArrayToRef(t.zz,0,i.zz),D.FromArrayToRef(t.yz,0,i.yz),D.FromArrayToRef(t.zx,0,i.zx),D.FromArrayToRef(t.xy,0,i.xy),s._sphericalPolynomial=i}function Nke(s,e,t,i,r){const n=s.getEngine().createRawCubeTexture(null,s.width,s.format,s.type,s.generateMipMaps,s.invertY,s.samplingMode,s._compression),a=Vk(n,e).then(()=>s);return s.onRebuildCallback=o=>({proxy:a,isReady:!0,isAsync:!0}),s._source=13,s._bufferViewArrayArray=e,s._lodGenerationScale=i,s._lodGenerationOffset=r,s._sphericalPolynomial=t,Vk(s,e).then(()=>(s.isReady=!0,s))}const O3t={GetEnvInfo:lee,CreateEnvTextureAsync:Oke,CreateImageDataArrayBufferViews:cee,UploadEnvLevelsAsync:m1e,UploadLevelsAsync:Vk,UploadEnvSpherical:uee};function lY(s,e,t,i){let r=i,n=0,a="";for(;r=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function $ue(s){let e=0,t="",i=!1;const r=[];for(;e=0&&s.charAt(e)!==t&&s.charAt(e)!==i;)e--;return e}function F3t(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pZ(s,e,t,i){let r=s.indexOf(e);if(r<0)return s;if(t){for(;r++=0&&f.push(_.substring(y+1))}n!=="void"&&f.push("return"),this._functionDescr.push({name:a,type:n,parameters:f,body:h,callIndex:0}),e=u+1;const p=t>0?this._sourceCode.substring(0,t):"",m=u+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&fe.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:r,parameters:n,body:a}=t;let o=0;for(;o{const x=[];let A=0,b=0;for(;A0?this._sourceCode.substring(0,l):"";const y=u+1{const u=c[0];return Fne(e.charAt(u-1))||Fne(e.charAt(u+a))?t[r]:o})}return e}}xv._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const B3t=/(flat\s)?\s*varying\s*.*/;class k3t{constructor(){this.shaderLanguage=0}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const i=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(i!==null){const r=i[1],n=i[2],a=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[n];if(a!==void 0){const o=a<0?a===-1?"int":"ivec"+-a:a===1?"uint":"uvec"+a,l=`_int_${n}_`;e=e.replace(i[0],`in ${o} ${l}; ${r} ${n};`),this._nativeProcessingContext.injectInVertexMain+=`${n} = ${r}(${l}); `,this._nativeProcessingContext.remappedAttributeNames[n]=l}else e=e.replace(i[0],`in ${r} ${n};`)}return e}varyingCheck(e,t){return B3t.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){var a;const r=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,n=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(n,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const o=e.search(/layout *\(location *= *0\) *out/g)!==-1;e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(r||o?"":`layout(location = 0) out vec4 glFragColor; `)+"void main(")}else if((a=this._nativeProcessingContext)!=null&&a.injectInVertexMain&&(e=pZ(e,"void main",this._nativeProcessingContext.injectInVertexMain)),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require layout (num_views = 2) in; `+e;return e}}class U3t{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+(typeof e=="string"?` `+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,r,n,a,o,l){const c=this._engine;if(c.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this._engine.getUniforms(this,i).forEach((d,f)=>{r[i[f]]=d}),this._uniforms=r;let h;for(h=0;h{a[d]=f}),l.push(...c.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n}_cacheFloat3(e,t,i,r){let n=this._valueCache[e];if(!n)return n=[t,i,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,n){let a=this._valueCache[e];if(!a)return a=[t,i,r,n],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==n&&(a[3]=n,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this._engine.setInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this._engine.setUInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this._engine.setFloat4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class z3t extends Mz{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class jTe{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function Bne(s,e){switch(s){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:return _native.Engine.TEXTURE_FORMAT_BC1;case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break}case 5:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break}case 6:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break}case 7:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break}case 12:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_BGRA8}break}}throw new R0(`Unsupported texture format or type: format ${s}, type ${e}.`,x_.UnsupportedTextureError)}function x9(s){switch(s){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${s}.`)}}function kne(s){switch(s){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+s+".")}}function V3t(s){switch(s){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${s}.`)}}function G3t(s){switch(s){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${s}.`)}}function W3t(s){switch(s){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${s}.`)}}function K3t(s){switch(s){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${s}.`)}}function H3t(s){switch(s){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${s}.`)}}function j3t(s){switch(s){case $.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case $.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case $.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case $.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case $.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${s}.`)}}const X3t={[$.PositionKind]:!0,[$.NormalKind]:!0,[$.TangentKind]:!0,[$.UVKind]:!0,[$.UV2Kind]:!0,[$.UV3Kind]:!0,[$.UV4Kind]:!0,[$.UV5Kind]:!0,[$.UV6Kind]:!0,[$.ColorKind]:!0,[$.ColorInstanceKind]:!0,[$.MatricesIndicesKind]:!0,[$.MatricesWeightsKind]:!0,[$.MatricesIndicesExtraKind]:!0,[$.MatricesWeightsExtraKind]:!0};function Y3t(s){switch(s){case $.BYTE:case $.SHORT:case $.INT:case $.FLOAT:return!0;case $.UNSIGNED_BYTE:case $.UNSIGNED_SHORT:case $.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${s}'`)}}function Fke(s,e){const t=e.getEngine(),i=e._pipelineContext;if(!(i!=null&&i.vertexBufferKindToType))return;let r=null;for(const n in s){const a=s[n];if(!a||!X3t[n])continue;const o=a.normalized?$.FLOAT:a.type,l=i.vertexBufferKindToType[n];(o!==$.FLOAT&&l===void 0||l!==void 0&&l!==o)&&(r||(r=t._getShaderProcessingContext(e.shaderLanguage,!1)),i.vertexBufferKindToType[n]=o,o!==$.FLOAT&&(r.vertexBufferKindToNumberOfComponents[n]=$.DeduceStride(n),Y3t(o)&&(r.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(r){const n=t._caps.parallelShaderCompile;t._caps.parallelShaderCompile=void 0,e._processShaderCodeAsync(null,t._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,r),t._caps.parallelShaderCompile=n}}class Q3t{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}const Bke=new Ae;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let s;Object.defineProperty(self,"_native",{get:()=>s,set:e=>{s=e,s&&Bke.notifyObservers(s)}})}function kke(){return new Promise(s=>{typeof _native>"u"?Bke.addOnce(e=>s(e)):s(_native)})}async function Uke(s,e){(await kke())[s]=e}class XTe extends Zm{}class $3t{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=a6._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const Une=[];class a6 extends vt{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:vt.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new $3t(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,this._fillModeWarningDisplayed=!1,_native.Engine.PROTOCOL_VERSION!==a6.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${a6.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback(()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()}),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Me.Log("Babylon Native (v"+vt.Version+") launched"),Me.LoadScript=function(r,n,a,o){Me.LoadFile(r,l=>{Function(l).apply(null),n&&n()},void 0,void 0,!1,(l,c)=>{a&&a("LoadScript Error",c)})},typeof URL>"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(r){return r}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function r(){const n=isNaN(arguments[0])?1:Number(arguments[0]);return n?Array.prototype.reduce.call(this,function(a,o){return Array.isArray(o)?a.push.apply(a,r.call(o,n-1)):a.push(o),a},[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new k3t,this.onNewSceneAddedObservable.add(r=>{const n=r.render;r.render=(...a)=>{this._commandBufferEncoder.beginCommandScope(),n.apply(r,a),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new Cx}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const r=this._normalizeIndexData(e),n=new XTe;return n.references=1,n.is32Bits=r.BYTES_PER_ELEMENT===4,r.byteLength&&(n.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,n.is32Bits,t??!1)),n}createVertexBuffer(e,t,i){const r=ArrayBuffer.isView(e)?e:new Float32Array(e),n=new XTe;return n.references=1,r.byteLength&&(n.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,t??!1)),n}_recordVertexArrayObject(e,t,i,r,n){r._checkedNonFloatVertexBuffers||(Fke(t,r),r._checkedNonFloatVertexBuffers=!0),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const a=r.getAttributesNames();for(let o=0;o=0){const c=a[o];let u=null;if(n&&(u=n[c]),u||(u=t[c]),u){const h=u.effectiveBuffer;h&&h.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,h.nativeVertexBuffer,l,u.effectiveByteOffset,u.effectiveByteStride,u.getSize(),j3t(u.type),u.normalized,u.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){const n=this._engine.createVertexArray();return this._recordVertexArrayObject(n,e,t,i,r),n}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,r=i.shaderProcessingContext;Une.length=0;for(let n=0;n{r(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,r){const n=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=new xv(t);a.processCode(),t=a.code;const o=new xv(i);o.processCode(),i=o.code,t=bi._ConcatenateShader(t,r),i=bi._ConcatenateShader(i,r);const l=()=>{var c;n.isCompiled=!0,(c=n.onCompiled)==null||c.call(n),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)n.program=this._engine.createProgramAsync(t,i,l,c=>{n.compilationError=c});else try{n.program=this._engine.createProgram(t,i),l()}catch(c){const u=c==null?void 0:c.message;throw new Error("SHADER ERROR"+(typeof u=="string"?` `+u:""))}return n.program}inlineShaderCode(e){const t=new xv(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let r=0;r{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL;break}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,G3t(this._stencilOpStencilFail),W3t(this._stencilOpDepthFail),K3t(this._stencilOpStencilDepthPass),V3t(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,n,a){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(a),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=H3t(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(e===0),this._alphaMode=e}setInt(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray4(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray4(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setArray(e,t){return e?this.setFloatArray(e,new Float32Array(t)):!1}setArray2(e,t){return e?this.setFloatArray2(e,new Float32Array(t)):!1}setArray3(e,t){return e?this.setFloatArray3(e,new Float32Array(t)):!1}setArray4(e,t){return e?this.setFloatArray4(e,new Float32Array(t)):!1}setMatrices(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setMatrix3x3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setMatrix2x2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat2(e,t,i){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat3(e,t,i,r){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat4(e,t,i,r,n){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setColor3(e,t){return e?(this.setFloat3(e,t.r,t.g,t.b),!0):!1}setColor4(e,t,i){return e?(this.setFloat4(e,t.r,t.g,t.b,i),!0):!1}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e.underlyingResource)}updateDynamicTexture(e,t,i,r=!1,n){if(r===void 0&&(r=!1),e&&e._hardwareTexture){const a=t.getCanvasTexture(),o=e._hardwareTexture.underlyingResource;this._engine.copyTexture(o,a),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,n,a,o,l=null,c=0,u=0,h=!1){const d=new zr(this,3);if(d.format=r,d.generateMipMaps=n,d.samplingMode=o,d.invertY=a,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=l,d.type=c,d._useSRGBBuffer=this._getUseSRGBBuffer(h,!n),this.updateRawTexture(d,e,r,a,l,c,d._useSRGBBuffer),d._hardwareTexture){const f=d._hardwareTexture.underlyingResource,p=x9(o);this._setTextureSampling(f,p)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,r,n,a,o,l,c=null,u=0){const h=new zr(this,11);if(h.baseWidth=t,h.baseHeight=i,h.baseDepth=r,h.width=t,h.height=i,h.depth=r,h.format=n,h.type=u,h.generateMipMaps=a,h.samplingMode=l,h.is2DArray=!0,h._hardwareTexture){const d=h._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(d,e,t,i,r,Bne(n,u),a,o);const f=x9(l);this._setTextureSampling(d,f)}return h.isReady=!0,this._internalTexturesCache.push(h),h}updateRawTexture(e,t,i,r,n=null,a=0,o=!1){if(e){if(t&&e._hardwareTexture){const l=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(l,t,e.width,e.height,Bne(i,a),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,n=3,a=null,o=null,l=null,c=null,u=null,h=null,d,f,p,m=!1){e=e||"";const g=e.substr(0,5)==="data:",_=g&&e.indexOf(";base64,")!==-1,y=c||new zr(this,1),v=e;this._transformTextureUrl&&!_&&!c&&!l&&(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),A=h||(x>-1?e.substring(x).toLowerCase():""),b=bJ(A);r&&r.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=n,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(m,t),this.doNotHandleContextLost||(y._buffer=l);let C=null;a&&!c&&(C=y.onLoadedObservable.add(a)),c||this._internalTexturesCache.push(y);const T=(w,P)=>{r&&r.removePendingData(y),e===v?(C&&y.onLoadedObservable.remove(C),Rt.UseFallbackTexture&&this.createTexture(Rt.FallbackTexture,t,y.invertY,r,n,null,o,l,y),o&&o((w||"Unknown error")+(Rt.UseFallbackTexture?" - Fallback texture was used":""),P)):(fe.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,y.invertY,r,n,a,o,l,y,u,h,d,f))};if(b)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const w=P=>{if(!y._hardwareTexture){r&&r.removePendingData(y);return}const M=y._hardwareTexture.underlyingResource;this._engine.loadTexture(M,P,!t,i,y._useSRGBBuffer,()=>{y.baseWidth=this._engine.getTextureWidth(M),y.baseHeight=this._engine.getTextureHeight(M),y.width=y.baseWidth,y.height=y.baseHeight,y.isReady=!0;const R=x9(n);this._setTextureSampling(M,R),r&&r.removePendingData(y),y.onLoadedObservable.notifyObservers(y),y.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(g&&l)if(l instanceof ArrayBuffer)w(new Uint8Array(l));else if(ArrayBuffer.isView(l))w(l);else if(typeof l=="string")w(new Uint8Array(Me.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else _?w(new Uint8Array(Me.DecodeBase64(e))):this._loadFile(e,P=>w(new Uint8Array(P)),void 0,void 0,!0,(P,M)=>{T("Unable to load "+(P&&P.responseURL,M))})}return y}wrapNativeTexture(e,t=!1,i=3){const r=new jTe(e,this._engine),n=new zr(this,0,!0);return n._hardwareTexture=r,n.baseWidth=this._engine.getTextureWidth(e),n.baseHeight=this._engine.getTextureHeight(e),n.width=n.baseWidth,n.height=n.baseHeight,n.isReady=!0,n.useMipMaps=t,this.updateTextureSamplingMode(i,n),n}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const r=t.generateStencil||!1,n=t.samples||1,a=i,o=new zr(this,12),l=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,c,r,!0,n);return a._framebufferDepthStencil=u,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((r,n)=>{const a=this.createCanvasImage();a.onload=()=>{try{const o=this._engine.createImageBitmap(a);r(o)}catch(o){n(`Error loading image ${a.src} with exception: ${o}`)}},a.onerror=o=>{n(`Error loading image ${a.src} with exception: ${o}`)},a.src=e})}createImageBitmap(e,t){return new Promise((i,r)=>{if(Array.isArray(e)){const n=e;if(n.length){const a=this._engine.createImageBitmap(n[0]);if(a){i(a);return}}}r("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,n=null,a=null,o,l=null,c=!1,u=0,h=0,d=null,f,p=!1,m=null){const g=d||new zr(this,7);g.isCube=!0,g.url=e,g.generateMipMaps=!r,g._lodGenerationScale=u,g._lodGenerationOffset=h,g._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(g._extension=l,g._files=i,g._buffer=m);const _=e.lastIndexOf(".");if((l||(_>-1?e.substring(_).toLowerCase():""))===".env"){const v=x=>{const A=lee(x);g.width=A.width,g.height=A.width,uee(g,A);const b=A.specular;if(!b)throw new Error("Nothing else parsed so far");g._lodGenerationScale=b.lodGenerationScale;const C=cee(x,A);g.format=5,g.type=0,g.generateMipMaps=!0,g.getEngine().updateTextureSamplingMode(xe.TRILINEAR_SAMPLINGMODE,g),g._isRGBD=!0,g.invertY=!0,this._engine.loadCubeTextureWithMips(g._hardwareTexture.underlyingResource,C,!1,g._useSRGBBuffer,()=>{g.isReady=!0,n&&n()},()=>{throw new Error("Could not load a native cube texture.")})};if(m)v(m);else{if(i&&i.length===6)throw new Error("Multi-file loading not allowed on env files.");{const x=(A,b)=>{a&&A&&a(A.status+" "+A.statusText,b)};this._loadFile(e,A=>{v(new Uint8Array(A,0,A.byteLength))},void 0,void 0,!0,x)}}}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");const v=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(v.map(x=>this._loadFileAsync(x,void 0,!0).then(A=>new Uint8Array(A,0,A.byteLength)))).then(x=>new Promise((A,b)=>{this._engine.loadCubeTexture(g._hardwareTexture.underlyingResource,x,!r,!0,g._useSRGBBuffer,A,b)})).then(()=>{g.isReady=!0,n&&n()},x=>{a&&a(`Failed to load cubemap: ${x.message}`,x)})}return this._internalTexturesCache.push(g),g}_createHardwareTexture(){return new jTe(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const r=new z3t(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=0){let n=!1,a=0,o=3,l=5,c=!1,u=1,h;t!==void 0&&typeof t=="object"?(n=!!t.generateMipMaps,a=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,l=t.format===void 0?5:t.format,c=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,u=t.samples??1,h=t.label):n=!!t,c=this._getUseSRGBBuffer(c,!n),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,fe.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=new zr(this,r),f=e.width??e,p=e.height??e,m=e.layers||0;if(m!==0)throw new Error("Texture layers are not supported in Babylon Native");const g=d._hardwareTexture.underlyingResource,_=Bne(l,a);return this._engine.initializeTexture(g,f,p,n,_,!0,c,u),this._setTextureSampling(g,x9(o)),d._useSRGBBuffer=c,d.baseWidth=f,d.baseHeight=p,d.width=f,d.height=p,d.depth=m,d.isReady=!0,d.samples=u,d.generateMipMaps=n,d.samplingMode=o,d.type=a,d.format=l,d.label=h,this._internalTexturesCache.push(d),d}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let r=!0,n=!1,a=!1,o,l=1;t!==void 0&&typeof t=="object"&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,a=!!t.noColorAttachment,o=t.colorAttachment,l=t.samples??1);const c=o||(a?null:this._createInternalTexture(e,t,!0,5)),u=e.width??e,h=e.height??e,d=this._engine.createFrameBuffer(c?c._hardwareTexture.underlyingResource:null,u,h,n,r,l);return i._framebuffer=d,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=l,i.setTextures(c),i}updateRenderTargetTextureSampleCount(e,t){return fe.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=x9(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,n){const a=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");a._framebufferDepthStencil?this._bindUnboundFramebuffer(a._framebufferDepthStencil):this._bindUnboundFramebuffer(a._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const r=e,n=this._normalizeIndexData(t);r.is32Bits=n.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(r.nativeIndexBuffer,n.buffer,n.byteOffset,n.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,r){const n=e,a=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(a.buffer,a.byteOffset,r??a.byteLength);this._engine.updateDynamicVertexBuffer(n.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,r=!1){const n=this._boundUniforms[e];if(!n)return!1;if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(n)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;return r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,this._activeChannel=e,!a||!a._hardwareTexture?!1:(this._setTextureWrapMode(a._hardwareTexture.underlyingResource,kne(t.wrapU),kne(t.wrapV),kne(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(n,a._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;!t||!t._hardwareTexture||t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const r=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,r)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,r,n,a,o=0,l=0,c=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,n,a=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,r,n,a,o,l,c,u){var h;if(r!==void 0&&r!==-1)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture((h=e._hardwareTexture)==null?void 0:h.underlyingResource,n??0,c??0,u??0,t,i,(a==null?void 0:a.buffer)??null,(a==null?void 0:a.byteOffset)??0,(a==null?void 0:a.byteLength)??0).then(d=>(a||(a=new Uint8Array(d)),a))}}a6.PROTOCOL_VERSION=8;a6._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new zke:new Cx};class zke extends Cx{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var Zue;(function(s){s.LowPower="low-power",s.HighPerformance="high-performance"})(Zue||(Zue={}));var que;(function(s){s.DepthClipControl="depth-clip-control",s.Depth32FloatStencil8="depth32float-stencil8",s.TextureCompressionBC="texture-compression-bc",s.TextureCompressionETC2="texture-compression-etc2",s.TextureCompressionASTC="texture-compression-astc",s.TimestampQuery="timestamp-query",s.IndirectFirstInstance="indirect-first-instance",s.ShaderF16="shader-f16",s.RG11B10UFloatRenderable="rg11b10ufloat-renderable",s.BGRA8UnormStorage="bgra8unorm-storage",s.Float32Filterable="float32-filterable"})(que||(que={}));var Jue;(function(s){s.Unmapped="unmapped",s.Pending="pending",s.Mapped="mapped"})(Jue||(Jue={}));var Ds;(function(s){s[s.MapRead=1]="MapRead",s[s.MapWrite=2]="MapWrite",s[s.CopySrc=4]="CopySrc",s[s.CopyDst=8]="CopyDst",s[s.Index=16]="Index",s[s.Vertex=32]="Vertex",s[s.Uniform=64]="Uniform",s[s.Storage=128]="Storage",s[s.Indirect=256]="Indirect",s[s.QueryResolve=512]="QueryResolve"})(Ds||(Ds={}));var ehe;(function(s){s[s.Read=1]="Read",s[s.Write=2]="Write"})(ehe||(ehe={}));var the;(function(s){s.E1d="1d",s.E2d="2d",s.E3d="3d"})(the||(the={}));var ihe;(function(s){s[s.CopySrc=1]="CopySrc",s[s.CopyDst=2]="CopyDst",s[s.TextureBinding=4]="TextureBinding",s[s.StorageBinding=8]="StorageBinding",s[s.RenderAttachment=16]="RenderAttachment"})(ihe||(ihe={}));var rhe;(function(s){s.E1d="1d",s.E2d="2d",s.E2dArray="2d-array",s.Cube="cube",s.CubeArray="cube-array",s.E3d="3d"})(rhe||(rhe={}));var she;(function(s){s.All="all",s.StencilOnly="stencil-only",s.DepthOnly="depth-only"})(she||(she={}));var nhe;(function(s){s.R8Unorm="r8unorm",s.R8Snorm="r8snorm",s.R8Uint="r8uint",s.R8Sint="r8sint",s.R16Uint="r16uint",s.R16Sint="r16sint",s.R16Float="r16float",s.RG8Unorm="rg8unorm",s.RG8Snorm="rg8snorm",s.RG8Uint="rg8uint",s.RG8Sint="rg8sint",s.R32Uint="r32uint",s.R32Sint="r32sint",s.R32Float="r32float",s.RG16Uint="rg16uint",s.RG16Sint="rg16sint",s.RG16Float="rg16float",s.RGBA8Unorm="rgba8unorm",s.RGBA8UnormSRGB="rgba8unorm-srgb",s.RGBA8Snorm="rgba8snorm",s.RGBA8Uint="rgba8uint",s.RGBA8Sint="rgba8sint",s.BGRA8Unorm="bgra8unorm",s.BGRA8UnormSRGB="bgra8unorm-srgb",s.RGB9E5UFloat="rgb9e5ufloat",s.RGB10A2UINT="rgb10a2uint",s.RGB10A2Unorm="rgb10a2unorm",s.RG11B10UFloat="rg11b10ufloat",s.RG32Uint="rg32uint",s.RG32Sint="rg32sint",s.RG32Float="rg32float",s.RGBA16Uint="rgba16uint",s.RGBA16Sint="rgba16sint",s.RGBA16Float="rgba16float",s.RGBA32Uint="rgba32uint",s.RGBA32Sint="rgba32sint",s.RGBA32Float="rgba32float",s.Stencil8="stencil8",s.Depth16Unorm="depth16unorm",s.Depth24Plus="depth24plus",s.Depth24PlusStencil8="depth24plus-stencil8",s.Depth32Float="depth32float",s.BC1RGBAUnorm="bc1-rgba-unorm",s.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",s.BC2RGBAUnorm="bc2-rgba-unorm",s.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",s.BC3RGBAUnorm="bc3-rgba-unorm",s.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",s.BC4RUnorm="bc4-r-unorm",s.BC4RSnorm="bc4-r-snorm",s.BC5RGUnorm="bc5-rg-unorm",s.BC5RGSnorm="bc5-rg-snorm",s.BC6HRGBUFloat="bc6h-rgb-ufloat",s.BC6HRGBFloat="bc6h-rgb-float",s.BC7RGBAUnorm="bc7-rgba-unorm",s.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",s.ETC2RGB8Unorm="etc2-rgb8unorm",s.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",s.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",s.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",s.ETC2RGBA8Unorm="etc2-rgba8unorm",s.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",s.EACR11Unorm="eac-r11unorm",s.EACR11Snorm="eac-r11snorm",s.EACRG11Unorm="eac-rg11unorm",s.EACRG11Snorm="eac-rg11snorm",s.ASTC4x4Unorm="astc-4x4-unorm",s.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",s.ASTC5x4Unorm="astc-5x4-unorm",s.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",s.ASTC5x5Unorm="astc-5x5-unorm",s.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",s.ASTC6x5Unorm="astc-6x5-unorm",s.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",s.ASTC6x6Unorm="astc-6x6-unorm",s.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",s.ASTC8x5Unorm="astc-8x5-unorm",s.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",s.ASTC8x6Unorm="astc-8x6-unorm",s.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",s.ASTC8x8Unorm="astc-8x8-unorm",s.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",s.ASTC10x5Unorm="astc-10x5-unorm",s.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",s.ASTC10x6Unorm="astc-10x6-unorm",s.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",s.ASTC10x8Unorm="astc-10x8-unorm",s.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",s.ASTC10x10Unorm="astc-10x10-unorm",s.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",s.ASTC12x10Unorm="astc-12x10-unorm",s.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",s.ASTC12x12Unorm="astc-12x12-unorm",s.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",s.Depth32FloatStencil8="depth32float-stencil8"})(nhe||(nhe={}));var ahe;(function(s){s.ClampToEdge="clamp-to-edge",s.Repeat="repeat",s.MirrorRepeat="mirror-repeat"})(ahe||(ahe={}));var ohe;(function(s){s.Nearest="nearest",s.Linear="linear"})(ohe||(ohe={}));var lhe;(function(s){s.Nearest="nearest",s.Linear="linear"})(lhe||(lhe={}));var che;(function(s){s.Never="never",s.Less="less",s.Equal="equal",s.LessEqual="less-equal",s.Greater="greater",s.NotEqual="not-equal",s.GreaterEqual="greater-equal",s.Always="always"})(che||(che={}));var uhe;(function(s){s[s.Vertex=1]="Vertex",s[s.Fragment=2]="Fragment",s[s.Compute=4]="Compute"})(uhe||(uhe={}));var hhe;(function(s){s.Uniform="uniform",s.Storage="storage",s.ReadOnlyStorage="read-only-storage"})(hhe||(hhe={}));var dhe;(function(s){s.Filtering="filtering",s.NonFiltering="non-filtering",s.Comparison="comparison"})(dhe||(dhe={}));var fhe;(function(s){s.Float="float",s.UnfilterableFloat="unfilterable-float",s.Depth="depth",s.Sint="sint",s.Uint="uint"})(fhe||(fhe={}));var phe;(function(s){s.WriteOnly="write-only",s.ReadOnly="read-only",s.ReadWrite="read-write"})(phe||(phe={}));var mhe;(function(s){s.Error="error",s.Warning="warning",s.Info="info"})(mhe||(mhe={}));var ghe;(function(s){s.Validation="validation",s.Internal="internal"})(ghe||(ghe={}));var _he;(function(s){s.Auto="auto"})(_he||(_he={}));var vhe;(function(s){s.PointList="point-list",s.LineList="line-list",s.LineStrip="line-strip",s.TriangleList="triangle-list",s.TriangleStrip="triangle-strip"})(vhe||(vhe={}));var yhe;(function(s){s.CCW="ccw",s.CW="cw"})(yhe||(yhe={}));var xhe;(function(s){s.None="none",s.Front="front",s.Back="back"})(xhe||(xhe={}));var Ahe;(function(s){s[s.Red=1]="Red",s[s.Green=2]="Green",s[s.Blue=4]="Blue",s[s.Alpha=8]="Alpha",s[s.All=15]="All"})(Ahe||(Ahe={}));var bhe;(function(s){s.Zero="zero",s.One="one",s.Src="src",s.OneMinusSrc="one-minus-src",s.SrcAlpha="src-alpha",s.OneMinusSrcAlpha="one-minus-src-alpha",s.Dst="dst",s.OneMinusDst="one-minus-dst",s.DstAlpha="dst-alpha",s.OneMinusDstAlpha="one-minus-dst-alpha",s.SrcAlphaSaturated="src-alpha-saturated",s.Constant="constant",s.OneMinusConstant="one-minus-constant"})(bhe||(bhe={}));var Che;(function(s){s.Add="add",s.Subtract="subtract",s.ReverseSubtract="reverse-subtract",s.Min="min",s.Max="max"})(Che||(Che={}));var She;(function(s){s.Keep="keep",s.Zero="zero",s.Replace="replace",s.Invert="invert",s.IncrementClamp="increment-clamp",s.DecrementClamp="decrement-clamp",s.IncrementWrap="increment-wrap",s.DecrementWrap="decrement-wrap"})(She||(She={}));var Ehe;(function(s){s.Uint16="uint16",s.Uint32="uint32"})(Ehe||(Ehe={}));var The;(function(s){s.Uint8x2="uint8x2",s.Uint8x4="uint8x4",s.Sint8x2="sint8x2",s.Sint8x4="sint8x4",s.Unorm8x2="unorm8x2",s.Unorm8x4="unorm8x4",s.Snorm8x2="snorm8x2",s.Snorm8x4="snorm8x4",s.Uint16x2="uint16x2",s.Uint16x4="uint16x4",s.Sint16x2="sint16x2",s.Sint16x4="sint16x4",s.Unorm16x2="unorm16x2",s.Unorm16x4="unorm16x4",s.Snorm16x2="snorm16x2",s.Snorm16x4="snorm16x4",s.Float16x2="float16x2",s.Float16x4="float16x4",s.Float32="float32",s.Float32x2="float32x2",s.Float32x3="float32x3",s.Float32x4="float32x4",s.Uint32="uint32",s.Uint32x2="uint32x2",s.Uint32x3="uint32x3",s.Uint32x4="uint32x4",s.Sint32="sint32",s.Sint32x2="sint32x2",s.Sint32x3="sint32x3",s.Sint32x4="sint32x4",s.UNORM10x10x10x2="unorm10-10-10-2"})(The||(The={}));var Mhe;(function(s){s.Vertex="vertex",s.Instance="instance"})(Mhe||(Mhe={}));var Rhe;(function(s){s.Beginning="beginning",s.End="end"})(Rhe||(Rhe={}));var Ihe;(function(s){s.Beginning="beginning",s.End="end"})(Ihe||(Ihe={}));var Phe;(function(s){s.Load="load",s.Clear="clear"})(Phe||(Phe={}));var whe;(function(s){s.Store="store",s.Discard="discard"})(whe||(whe={}));var Dhe;(function(s){s.Occlusion="occlusion",s.Timestamp="timestamp"})(Dhe||(Dhe={}));var Lhe;(function(s){s.Opaque="opaque",s.Premultiplied="premultiplied"})(Lhe||(Lhe={}));var Ohe;(function(s){s.Unknown="unknown",s.Destroyed="destroyed"})(Ohe||(Ohe={}));var Nhe;(function(s){s.Validation="validation",s.OutOfMemory="out-of-memory",s.Internal="internal"})(Nhe||(Nhe={}));class Vo{constructor(){this.shaderLanguage=0}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let n=0;n=0&&(d.push(o[h]),f.push(p))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=f}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new zt(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Vo.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,r,n)}setIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,r,n)}setUIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,r,n)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return(e=this.sources)==null?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)==null?void 0:e.fragment}}const q3t=4,J3t=65536,YTe={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Kd{static get KnownUBOs(){return Kd._SimplifiedKnownBindings?Kd._SimplifiedKnownUBOs:Kd._KnownUBOs}constructor(e,t=!1){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],t||this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Kd.KnownUBOs,t=[];for(const i in e){const r=e[i].binding;r.groupIndex!==-1&&(t[r.groupIndex]===void 0?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(YTe[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(YTe[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>J3t-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===q3t)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Kd._SimplifiedKnownBindings=!0;Kd._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}};Kd._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class e4t extends Vo{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=0,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0;const n=e.indexOf("["),a=e.indexOf("]");if(n>0&&a>0){const o=e.substring(n+1,a);r=+o,isNaN(r)&&(r=+i[o.trim()]),e=e.substr(0,n)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO uniform ${Vo.InternalsUBOName} { float yFactor_; float textureOutputHeight_; }; `,r=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+`##INJECTCODE## `+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,r=/(flat\s)?\s*\bin\b/,n=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?r:!t&&this._vertexIsGLES3?i:n).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const r=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,a=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,l=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?r:a).exec(e);if(l!==null){const c=l[1]??"",u=l[2],h=l[3];let d;t?(d=this._webgpuProcessingContext.availableVaryings[h],this._missingVaryings[d]="",d===void 0&&fe.Warn(`Invalid fragment shader: The varying named "${h}" is not declared in the vertex shader! This declaration will be ignored.`)):(d=this._webgpuProcessingContext.getVaryingNextLocation(u,this._getArraySize(h,u,i)[2]),this._webgpuProcessingContext.availableVaryings[h]=d,this._missingVaryings[d]=`layout(location = ${d}) ${c} in ${u} ${h};`),e=e.replace(l[0],d===void 0?"":`layout(location = ${d}) ${c} ${t?"in":"out"} ${u} ${h};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=/\s*in\s+(\S+)\s+(\S+)\s*;/gm,r=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,a=(this._vertexIsGLES3?i:r).exec(e);if(a!==null){const o=a[1],l=a[2],c=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(l,o,t)[2]);this._webgpuProcessingContext.availableAttributes[l]=c,this._webgpuProcessingContext.orderedAttributes[c]=l;const u=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[l];if(u!==void 0){const h=u<0?u===-1?"int":"ivec"+-u:u===1?"uint":"uvec"+u,d=`_int_${l}_`;e=e.replace(a[0],`layout(location = ${c}) in ${h} ${d}; ${o} ${l} = ${o}(${d});`)}else e=e.replace(a[0],`layout(location = ${c}) in ${o} ${l};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(n!==null){let a=n[1],o=n[2];if(a.indexOf("sampler")===0||a.indexOf("sampler")===1){let l=0;[o,a,l]=this._getArraySize(o,a,i);let c=this._webgpuProcessingContext.availableTextures[o];if(!c){c={autoBindSampler:!0,isTextureArray:l>0,isStorageTexture:!1,textures:[],sampleType:"float"};for(let C=0;C<(l||1);++C)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=Vo._SamplerTypeByWebGLSamplerType[a]??"sampler",h=!!Vo._IsComparisonSamplerByWebGPUSamplerType[u],d=h?"comparison":"filtering",f=o+"Sampler";let p=this._webgpuProcessingContext.availableSamplers[f];p||(p={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const m=a.charAt(0)==="u"?"u":a.charAt(0)==="i"?"i":"";m&&(a=a.substr(1));const g=h?"depth":m==="u"?"uint":m==="i"?"sint":"float";c.sampleType=g;const _=l>0,y=p.binding.groupIndex,v=p.binding.bindingIndex,x=Vo._SamplerFunctionByWebGLSamplerType[a],A=Vo._TextureTypeByWebGLSamplerType[a],b=Vo._GpuTextureViewDimensionByWebGPUTextureType[A];if(!_)l=1,e=`layout(set = ${y}, binding = ${v}) uniform ${u} ${f}; layout(set = ${c.textures[0].groupIndex}, binding = ${c.textures[0].bindingIndex}) uniform ${m}${A} ${o}Texture; #define ${o} ${m}${x}(${o}Texture, ${f})`;else{const C=[];C.push(`layout(set = ${y}, binding = ${v}) uniform ${m}${u} ${f};`),e=` `;for(let T=0;T0?` `:""}#define ${o}${T} ${m}${x}(${o}Texture${T}, ${f})`}e=C.join(` `)+e,this._textureArrayProcessing.push(o)}this._webgpuProcessingContext.availableTextures[o]=c,this._webgpuProcessingContext.availableSamplers[f]=p,this._addSamplerBindingDescription(f,p,!t);for(let C=0;C=0,c=` glFragCoord_ = gl_FragCoord; if (yFactor_ == 1.) { glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; } `,u=l?`vec4 glFragCoord_; `:"",h=e.search(/layout *\(location *= *0\) *out/g)!==-1;if(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/gl_FragCoord/g,"glFragCoord_"),!this._fragmentIsGLES3)e=e.replace(/void\s+?main\s*\(/g,(a||h?"":`layout(location = 0) out vec4 glFragColor; `)+"void main(");else{const d=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);d!==null&&(e=e.substring(0,d.index)+"layout(location = 0) "+e.substring(d.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",u),l&&(e=pZ(e,"void main",c))}else if(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex"),e=e.replace(/gl_VertexID/g,"gl_VertexIndex"),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require layout (num_views = 2) in; `+e;if(!i){const l=e.lastIndexOf("}");e=e.substring(0,l),e+=`gl_Position.y *= yFactor_; `,e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let r=i.exec(e);for(;r!==null;){const n=r[1];let a=+n;this._preProcessors&&isNaN(a)&&(a=+this._preProcessors[n.trim()]),e=e.replace(r[0],t+a),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { `;for(const r of this._webgpuProcessingContext.leftOverUniforms)r.length>0?i+=` ${r.type} ${r.name}[${r.length}]; `:i+=` ${r.type} ${r.name}; `;return i+=`}; `,i}finalizeShaders(e,t){for(let r=0;r0&&(t=n+` `+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const Vke="helperFunctions",Gke=`const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;} fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);} fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(0.0),vec3f(1.0));} fn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);} fn maxEps(x: f32)->f32 {return max(x,Epsilon);} fn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));} fn absEps(x: f32)->f32 {return abs(x)+Epsilon;} fn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f( vec3(i0.x,i1.x,i2.x), vec3(i0.y,i1.y,i2.y), vec3(i0.z,i1.z,i2.z) );return outMatrix;} fn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det, b11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det, b21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);} #if USE_EXACT_SRGB_CONVERSIONS fn toLinearSpaceExact(color: vec3)->vec3 {let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));} fn toGammaSpaceExact(color: vec3)->vec3 {let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));} #endif fn toLinearSpace(color: f32)->f32 { #if USE_EXACT_SRGB_CONVERSIONS var nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045); #else return pow(color,LinearEncodePowerApprox); #endif } fn toLinearSpaceVec3(color: vec3)->vec3 { #if USE_EXACT_SRGB_CONVERSIONS return toLinearSpaceExact(color); #else return pow(color,vec3(LinearEncodePowerApprox)); #endif } fn toLinearSpaceVec4(color: vec4)->vec4 { #if USE_EXACT_SRGB_CONVERSIONS return vec4f(toLinearSpaceExact(color.rgb),color.a); #else return vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a); #endif } fn toGammaSpace(color: vec4)->vec4 { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toGammaSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); #endif } fn toGammaSpaceVec3(color: vec3)->vec3 { #if USE_EXACT_SRGB_CONVERSIONS return toGammaSpaceExact(color); #else return pow(color,vec3(GammaEncodePowerApprox)); #endif } fn squareVec3(value: vec3)->vec3 {return value*value;} fn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;} fn getLuminance(color: vec3)->f32 {return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} fn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} fn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;} const rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); } fn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;} fn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} `;de.IncludesShadersStoreWGSL[Vke]=Gke;const Wke={name:Vke,shader:Gke},Kke=Object.freeze(Object.defineProperty({__proto__:null,helperFunctionsWGSL:Wke},Symbol.toStringTag,{value:"Module"})),t4t="fresnelFunction",i4t=`#ifdef FRESNEL fn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32 {let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} #endif `;de.IncludesShadersStoreWGSL[t4t]=i4t;const r4t="meshUboDeclaration",s4t=`struct Mesh {world : mat4x4, visibility : f32,};var mesh : Mesh; #define WORLD_UBO `;de.IncludesShadersStoreWGSL[r4t]=s4t;const n4t="sceneUboDeclaration",a4t=`struct Scene {viewProjection : mat4x4, #ifdef MULTIVIEW viewProjectionR : mat4x4, #endif view : mat4x4, projection : mat4x4, vEyePosition : vec4,};var scene : Scene; `;de.IncludesShadersStoreWGSL[n4t]=a4t;const o4t="decalFragment",l4t=`#ifdef DECAL var decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a; #ifdef GAMMADECAL decalTempColor=toLinearSpaceVec3(decalColor.rgb); #endif #ifdef DECAL_SMOOTHALPHA decalTempAlpha=decalColor.a*decalColor.a; #endif surfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha); #endif `;de.IncludesShadersStoreWGSL[o4t]=l4t;const QTe="fragmentOutputs.fragDepth",c4t="uniforms",u4t="internals",h4t={texture_1d:"1d",texture_2d:"2d",texture_2d_array:"2d-array",texture_3d:"3d",texture_cube:"cube",texture_cube_array:"cube-array",texture_multisampled_2d:"2d",texture_depth_2d:"2d",texture_depth_2d_array:"2d-array",texture_depth_cube:"cube",texture_depth_cube_array:"cube-array",texture_depth_multisampled_2d:"2d",texture_storage_1d:"1d",texture_storage_2d:"2d",texture_storage_2d_array:"2d-array",texture_storage_3d:"3d",texture_external:null};class d4t extends Vo{constructor(){super(...arguments),this.shaderLanguage=1,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0,this.pureMode=!1}preProcessor(e,t,i,r,n){for(const a in i){if(a==="__VERSION__")continue;const o=i[a];(!isNaN(parseInt(o))||!isNaN(parseFloat(o)))&&(e=`const ${a} = ${o}; `+e)}return e}_getArraySize(e,t,i){let r=0;const n=t.lastIndexOf(">");if(t.indexOf("array")>=0&&n>0){let a=n;for(;a>0&&t.charAt(a)!==" "&&t.charAt(a)!==",";)a--;const o=t.substring(a+1,n);for(r=+o,isNaN(r)&&(r=+i[o.trim()]);a>0&&(t.charAt(a)===" "||t.charAt(a)===",");)a--;t=t.substring(t.indexOf("<")+1,a+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=this.pureMode?"":`struct ${Vo.InternalsUBOName} { yFactor_: f32, textureOutputHeight_: f32, }; var ${u4t} : ${Vo.InternalsUBOName}; `;return e.indexOf(t)!==-1?e:t+$ue(e)}varyingCheck(e){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const n=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(n!==null){const a=n[1]??"perspective",o=n[2]??"center",l=n[4],c=n[3],u=a==="flat"?`@interpolate(${a})`:`@interpolate(${a}, ${o})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[c],h===void 0&&fe.Warn(`Invalid fragment shader: The varying named "${c}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(l,this._getArraySize(c,l,i)[2]),this._webgpuProcessingContext.availableVaryings[c]=h,this._varyingsWGSL.push(` @location(${h}) ${u} ${c} : ${l},`),this._varyingNamesWGSL.push(c)),e=""}return e}attributeProcessor(e,t){const r=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const n=r[2],a=r[1],o=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(a,n,t)[2]);this._webgpuProcessingContext.availableAttributes[a]=o,this._webgpuProcessingContext.orderedAttributes[o]=a;const l=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[a];if(l!==void 0){const c=l<0?l===-1?"i32":"vec"+-l+"":l===1?"u32":"vec"+l+"",u=`_int_${a}_`;this._attributesInputWGSL.push(`@location(${o}) ${u} : ${c},`),this._attributesWGSL.push(`${a} : ${n},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${a} = ${n}(vertexInputs_.${u});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${o}) ${a} : ${n},`),this._attributesWGSL.push(`${a} : ${n},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${a} = vertexInputs_.${a};`);e=""}return e}uniformProcessor(e,t,i){const r=this.uniformRegexp.exec(e);if(r!==null){const n=r[2],a=r[1];this._addUniformToLeftOverUBO(a,n,i),e=""}return e}textureProcessor(e,t,i){const r=this.textureRegexp.exec(e);if(r!==null){const n=r[1],a=r[2],o=!!r[3],l=r[4],c=l.indexOf("storage")>0,u=r[6],h=c?u.substring(0,u.indexOf(",")).trim():null;let d=o?this._getArraySize(n,a,i)[2]:0,f=this._webgpuProcessingContext.availableTextures[n];if(f)d=f.textures.length;else{f={isTextureArray:d>0,isStorageTexture:c,textures:[],sampleType:"float"},d=d||1;for(let _=0;_0,m=h4t[l],g=p?"depth":u==="u32"?"uint":u==="i32"?"sint":"float";if(f.sampleType=g,m===void 0)throw`Can't get the texture dimension corresponding to the texture function "${l}"!`;for(let _=0;_=0&&!this.pureMode?` if (internals.yFactor_ == 1.) { fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; } `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const r=this._buildLeftOverUBO();e=r+e,t=r+t,e=e.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let n=`struct VertexInputs { @builtin(vertex_index) vertexIndex : u32, @builtin(instance_index) instanceIndex : u32, `;this._attributesInputWGSL.length>0&&(n+=this._attributesInputWGSL.join(` `)),n+=` }; var vertexInputs`+(this._hasNonFloatAttribute?"_":"")+` : VertexInputs; `,this._hasNonFloatAttribute&&(n+=`struct VertexInputs_ { vertexIndex : u32, instanceIndex : u32, `,n+=this._attributesWGSL.join(` `),n+=` }; var vertexInputs : VertexInputs_; `);let a=`struct FragmentInputs { @builtin(position) position : vec4, `;this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join(` `)),a+=` }; var vertexOutputs : FragmentInputs; `,e=n+a+e;let o=` vertexInputs${this._hasNonFloatAttribute?"_":""} = input; `;this._hasNonFloatAttribute&&(o+=`vertexInputs.vertexIndex = vertexInputs_.vertexIndex; vertexInputs.instanceIndex = vertexInputs_.instanceIndex; `,o+=this._attributesConversionCodeWGSL.join(` `),o+=` `);const l=this.pureMode?" return vertexOutputs;":` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; return vertexOutputs;`;let c=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")!==-1;e=(c?`diagnostic(off, derivative_uniformity); `:"")+pZ(e,"fn main",o,l),t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),this.pureMode||(t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy"));let u=`struct FragmentInputs { @builtin(position) position : vec4, @builtin(front_facing) frontFacing : bool, `;this._varyingsWGSL.length>0&&(u+=this._varyingsWGSL.join(` `)),u+=` }; var fragmentInputs : FragmentInputs; `;let h=`struct FragmentOutputs { `,d=/const SCENE_MRT_COUNT = (\d+);/,f=t.match(d),p=0;if(f){const v=parseInt(f[1]);if(v>0){for(let x=0;x, `,p++;t.indexOf("MRT_AND_COLOR")!==-1&&(h+=` @location(${p}) color : vec4, `,p++)}}d=/oitDepthSampler/,f=t.match(d),f&&(h+=` @location(${p++}) depth : vec2, `,h+=` @location(${p++}) frontColor : vec4, `,h+=` @location(${p++}) backColor : vec4, `),p===0&&(h+=` @location(0) color : vec4, `,p++);let m=!1,g=0;for(;!m&&(g=t.indexOf(QTe,g),!(g<0));){const v=g;for(m=!0;g>1&&t.charAt(g)!==` `;){if(t.charAt(g)==="/"&&t.charAt(g-1)==="/"){m=!1;break}g--}g=v+QTe.length}m&&(h+=` @builtin(frag_depth) fragDepth: f32, `),h+=`}; var fragmentOutputs : FragmentOutputs; `,t=u+h+t;const _=` fragmentInputs = input; `+i,y=" return fragmentOutputs;";return c=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")!==-1,t=(c?`diagnostic(off, derivative_uniformity); `:"")+pZ(t,"fn main",_,y),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { `;for(const n of this._webgpuProcessingContext.leftOverUniforms){const a=n.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=Vo.UniformSizes[a];if(n.length>0)if(o<=2){const l=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${l} { @size(16) el: ${a}, }`,this._stridedUniformArrays.push(n.name),r+=` @align(16) ${n.name} : array<${l}, ${n.length}>, `}else r+=` ${n.name} : array<${n.type}, ${n.length}>, `;else r+=` ${n.name} : ${n.type}, `}return r+=`}; `,r=`${i} ${r}`,r+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${c4t} : ${e}; `,r}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const r=i.exec(e);if(r===null)break;const n=r[1],a=r[2],o=n.length-7,l=n.lastIndexOf("Sampler")===o?n.substring(0,o):null,c=a==="sampler_comparison"?"comparison":"filtering";if(l){const p=this._webgpuProcessingContext.availableTextures[l];p&&(p.autoBindSampler=!0)}let u=this._webgpuProcessingContext.availableSamplers[n];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c},this._webgpuProcessingContext.availableSamplers[n]=u),this._addSamplerBindingDescription(n,u,t);const h=e.substring(0,r.index),d=`@group(${u.binding.groupIndex}) @binding(${u.binding.bindingIndex}) `,f=e.substring(r.index);e=h+d+f,i.lastIndex+=d.length}return e}_processCustomBuffers(e,t){var r;const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const n=i.exec(e);if(n===null)break;const a=n[1],o=n[3];let l=n[4];const c=n[5];let u=this._webgpuProcessingContext.availableBuffers[l];if(!u){const g=a==="uniform"?Kd.KnownUBOs[c]:null;let _;g?(l=c,_=g.binding,_.groupIndex===-1&&(_=(r=this._webgpuProcessingContext.availableBuffers[l])==null?void 0:r.binding,_||(_=this._webgpuProcessingContext.getNextFreeUBOBinding()))):_=this._webgpuProcessingContext.getNextFreeUBOBinding(),u={binding:_},this._webgpuProcessingContext.availableBuffers[l]=u}this._addBufferBindingDescription(l,this._webgpuProcessingContext.availableBuffers[l],o==="read_write"?"storage":a==="storage"?"read-only-storage":"uniform",t);const h=u.binding.groupIndex,d=u.binding.bindingIndex,f=e.substring(0,n.index),p=`@group(${h}) @binding(${d}) `,m=e.substring(n.index);e=f+p+m,i.lastIndex+=p.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*?)\\]`,"g"),`${t}[$1].el`);return e}}class us{static ComputeNumMipmapLevels(e,t){return At.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"rgb9e5ufloat":case"rg11b10ufloat":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":case"stencil8":return 0;case"r16uint":case"r16sint":case"rg16uint":case"rg16sint":case"rgba16uint":case"rgba16sint":case"depth16unorm":return 5;case"r16float":case"rg16float":case"rgba16float":return 2;case"r32uint":case"r32sint":case"rg32uint":case"rg32sint":case"rgba32uint":case"rgba32sint":return 7;case"r32float":case"rg32float":case"rgba32float":case"depth32float":case"depth32float-stencil8":case"depth24plus":case"depth24plus-stencil8":return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return{width:1,height:1,length:1};case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":return{width:1,height:1,length:2};case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2uint":case"rgb10a2unorm":case"rg11b10ufloat":return{width:1,height:1,length:4};case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return{width:1,height:1,length:8};case"rgba32uint":case"rgba32sint":case"rgba32float":return{width:1,height:1,length:16};case"stencil8":throw"No fixed size for Stencil8 format!";case"depth16unorm":return{width:1,height:1,length:2};case"depth24plus":throw"No fixed size for Depth24Plus format!";case"depth24plus-stencil8":throw"No fixed size for Depth24PlusStencil8 format!";case"depth32float":return{width:1,height:1,length:4};case"depth32float-stencil8":return{width:1,height:1,length:5};case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":return{width:4,height:4,length:16};case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":return{width:4,height:4,length:8};case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":return{width:4,height:4,length:8};case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-rg11unorm":case"eac-rg11snorm":return{width:4,height:4,length:16};case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":return{width:4,height:4,length:16};case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":return{width:5,height:4,length:16};case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":return{width:5,height:5,length:16};case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":return{width:6,height:5,length:16};case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":return{width:6,height:6,length:16};case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":return{width:8,height:5,length:16};case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":return{width:8,height:6,length:16};case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":return{width:8,height:8,length:16};case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":return{width:10,height:5,length:16};case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":return{width:10,height:6,length:16};case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":return{width:10,height:8,length:16};case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":return{width:10,height:10,length:16};case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":return{width:12,height:10,length:16};case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return e.close!==void 0}static IsImageBitmapArray(e){return Array.isArray(e)&&e[0].close!==void 0}static IsCompressedFormat(e){switch(e){case"bc7-rgba-unorm-srgb":case"bc7-rgba-unorm":case"bc6h-rgb-float":case"bc6h-rgb-ufloat":case"bc5-rg-snorm":case"bc5-rg-unorm":case"bc4-r-snorm":case"bc4-r-unorm":case"bc3-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc1-rgba-unorm-srgb":case"bc1-rgba-unorm":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return"depth16unorm";case 16:return"depth24plus";case 13:return"depth24plus-stencil8";case 14:return"depth32float";case 18:return"depth32float-stencil8";case 19:return"stencil8";case 36492:return i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";case 36495:return"bc6h-rgb-ufloat";case 36494:return"bc6h-rgb-float";case 33779:return i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";case 33778:return i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";case 33777:case 33776:return i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";case 37808:return i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";case 36196:case 37492:return i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";case 37496:return i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm"}switch(e){case 3:switch(t){case 6:return"r8snorm";case 7:return"rg8snorm";case 4:throw"RGB format not supported in WebGPU";case 8:return"r8sint";case 9:return"rg8sint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8sint";default:return"rgba8snorm"}case 0:switch(t){case 6:return"r8unorm";case 7:return"rg8unorm";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?"rgba8unorm-srgb":"rgba8unorm";case 12:return i?"bgra8unorm-srgb":"bgra8unorm";case 8:return"r8uint";case 9:return"rg8uint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8uint";case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return"rgba8unorm"}case 4:switch(t){case 8:return"r16sint";case 9:return"rg16sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba16sint";default:return"rgba16sint"}case 5:switch(t){case 8:return"r16uint";case 9:return"rg16uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba16uint";default:return"rgba16uint"}case 6:switch(t){case 8:return"r32sint";case 9:return"rg32sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba32sint";default:return"rgba32sint"}case 7:switch(t){case 8:return"r32uint";case 9:return"rg32uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba32uint";default:return"rgba32uint"}case 1:switch(t){case 6:return"r32float";case 7:return"rg32float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return"rgba32float";default:return"rgba32float"}case 2:switch(t){case 6:return"r16float";case 7:return"rg16float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return"rgba16float";default:return"rgba16float"}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return"rg11b10ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return"rg11b10ufloat"}case 14:switch(t){case 5:return"rgb9e5ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return"rgb9e5ufloat"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:return"rgb10a2unorm";case 11:return"rgb10a2uint";default:return"rgb10a2unorm"}}return i?"rgba8unorm-srgb":"rgba8unorm"}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"bc4-r-unorm":case"bc4-r-snorm":case"r16uint":case"r16sint":case"depth16unorm":case"r16float":case"r32uint":case"r32sint":case"r32float":case"depth32float":case"stencil8":case"depth24plus":case"eac-r11unorm":case"eac-r11snorm":return 1;case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth32float-stencil8":case"bc5-rg-unorm":case"bc5-rg-snorm":case"rg16uint":case"rg16sint":case"rg16float":case"rg32uint":case"rg32sint":case"rg32float":case"depth24plus-stencil8":case"eac-rg11unorm":case"eac-rg11snorm":return 2;case"rgb9e5ufloat":case"rg11b10ufloat":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":return 3;case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba32uint":case"rgba32sint":case"rgba32float":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case"stencil8":case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static GetDepthFormatOnly(e){switch(e){case"depth16unorm":return"depth16unorm";case"depth24plus":return"depth24plus";case"depth24plus-stencil8":return"depth24plus";case"depth32float":return"depth32float";case"depth32float-stencil8":return"depth32float"}return e}static GetSample(e){return e>1?4:1}}class XQ{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t;return((t=this._webgpuMSAATexture)==null?void 0:t[e])??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),t===-1&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e==null||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format="rgba8unorm",this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,n,a,o,l){let c="2d",u=1;r?(c=i?"cube-array":"cube",u=6*(l||1)):n?(c="3d",u=1):i&&(c="2d-array",u=l);const h=us.GetDepthFormatOnly(this.format),d=us.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:`TextureView${n?"3D":r?"Cube":"2D"}${i?"_Array"+u:""}_${a}x${o}_${t?"wmips":"womips"}_${this.format}_${c}`,format:h,dimension:c,mipLevelCount:t?At.ILog2(Math.max(a,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:u,aspect:d})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const i=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=i}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;(e=this._webgpuTexture)==null||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)==null||t.destroy(),this.reset()}}const f4t=` const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f)); const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f)); varying vTex: vec2f; @vertex fn main(input : VertexInputs) -> FragmentInputs { vertexOutputs.vTex = tex[input.vertexIndex]; vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0); } `,p4t=` var imgSampler: sampler; var img: texture_2d; varying vTex: vec2f; @fragment fn main(input: FragmentInputs) -> FragmentOutputs { fragmentOutputs.color = textureSample(img, imgSampler, input.vTex); } `,Hke=` const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f)); const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f)); var img: texture_2d; #ifdef INVERTY varying vTextureSize: vec2f; #endif @vertex fn main(input : VertexInputs) -> FragmentInputs { #ifdef INVERTY vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0)); #endif vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0); } `,m4t=` var img: texture_2d; #ifdef INVERTY varying vTextureSize: vec2f; #endif @fragment fn main(input: FragmentInputs) -> FragmentOutputs { #ifdef INVERTY var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0); #else var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0); #endif #ifdef PREMULTIPLYALPHA fragmentOutputs.color = vec4f(color.rgb * color.a, color.a); #endif fragmentOutputs.color = color; } `,g4t=Hke,_4t=` var img: texture_2d; uniform ofstX: f32; uniform ofstY: f32; uniform width: f32; uniform height: f32; #ifdef INVERTY varying vTextureSize: vec2f; #endif @fragment fn main(input: FragmentInputs) -> FragmentOutputs { if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) { discard; } if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) { discard; } #ifdef INVERTY var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0); #else var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0); #endif #ifdef PREMULTIPLYALPHA color = vec4f(color.rgb * color.a, color.a); #endif fragmentOutputs.color = color; } `,v4t=` const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f)); @vertex fn main(input : VertexInputs) -> FragmentInputs { vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0); } `,y4t=` uniform color: vec4f; @fragment fn main(input: FragmentInputs) -> FragmentOutputs { fragmentOutputs.color = uniforms.color; } `,x4t=` struct VertexOutput { @builtin(position) Position : vec4, @location(0) fragUV : vec2 } @vertex fn main( @builtin(vertex_index) VertexIndex : u32 ) -> VertexOutput { var pos = array, 4>( vec2(-1.0, 1.0), vec2( 1.0, 1.0), vec2(-1.0, -1.0), vec2( 1.0, -1.0) ); var tex = array, 4>( vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0) ); var output: VertexOutput; output.Position = vec4(pos[VertexIndex], 0.0, 1.0); output.fragUV = tex[VertexIndex]; return output; } `,A4t=` @group(0) @binding(0) var videoSampler: sampler; @group(0) @binding(1) var videoTexture: texture_external; @fragment fn main( @location(0) fragUV: vec2 ) -> @location(0) vec4 { return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); } `,b4t=` @group(0) @binding(0) var videoSampler: sampler; @group(0) @binding(1) var videoTexture: texture_external; @fragment fn main( @location(0) fragUV: vec2 ) -> @location(0) vec4 { return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); } `;var Kp;(function(s){s[s.MipMap=0]="MipMap",s[s.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",s[s.Clear=2]="Clear",s[s.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(Kp||(Kp={}));var P5;(function(s){s[s.DontInvertY=0]="DontInvertY",s[s.InvertY=1]="InvertY"})(P5||(P5={}));const $Te=[{vertex:f4t,fragment:p4t},{vertex:Hke,fragment:m4t},{vertex:v4t,fragment:y4t},{vertex:g4t,fragment:_4t}],O1={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class C4t{constructor(e,t,i,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._bufferManager=i,r.indexOf("rg11b10ufloat-renderable")!==-1){const n=Object.keys(O1);O1.rg11b10ufloat=O1[n[n.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,Ds.Uniform|Ds.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=Kp.MipMap,i){const r=t===Kp.MipMap?1:t===Kp.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Kp.Clear?8:t===Kp.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let n=this._pipelines[e][r];if(!n){let a="";(t===Kp.InvertYPremultiplyAlpha||t===Kp.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(a+=`#define INVERTY `),i.premultiplyAlpha&&(a+=`#define PREMULTIPLYALPHA `));let o=this._compiledShaders[r];if(!o){let c=$Te[t].vertex,u=$Te[t].fragment;const h={defines:a.split(` `),indexParameters:null,isFragment:!1,shouldUseHighPrecisionShader:!0,processor:this._engine._getShaderProcessor(1),supportsUniformBuffers:!0,shadersRepository:"",includesShadersStore:{},version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._engine._getShaderProcessingContext(1,!0),isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};oge(h),h.processor.pureMode=!0,nZ(c,h,m=>{c=m},this._engine),h.isFragment=!0,nZ(u,h,m=>{u=m},this._engine);const d=lge(c,u,h);h.processor.pureMode=!1;const f=this._device.createShaderModule({code:d.vertexCode}),p=this._device.createShaderModule({code:d.fragmentCode});o=this._compiledShaders[r]=[f,p]}const l=this._device.createRenderPipeline({layout:"auto",vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});n=this._pipelines[e][r]=[l,l.getBindGroupLayout(0)]}return n}_getVideoPipeline(e,t=P5.DontInvertY){const i=t===P5.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let n=this._videoCompiledShaders[i];if(!n){const o=this._device.createShaderModule({code:x4t}),l=this._device.createShaderModule({code:i===0?A4t:b4t});n=this._videoCompiledShaders[i]=[o,l]}const a=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:"auto",vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});r=this._videoPipelines[e][i]=[a,a.getBindGroupLayout(0)]}return r}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,r=!1,n){var p,m;const a=n===void 0,[o,l]=this._getVideoPipeline(i,r?P5.InvertY:P5.DontInvertY);a&&(n=this._device.createCommandEncoder({})),(p=n.pushDebugGroup)==null||p.call(n,`copy video to texture - invertY=${r}`);const c=t._hardwareTexture,u={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${r?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:c.underlyingResource.createView({format:i,dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"}),loadOp:"load",storeOp:"store"}]},h=n.beginRenderPass(u),d={layout:l,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},f=this._device.createBindGroup(d);h.setPipeline(o),h.setBindGroup(0,f),h.draw(4,1,0,0),h.end(),(m=n.popDebugGroup)==null||m.call(n),a&&(this._device.queue.submit([n.finish()]),n=null)}invertYPreMultiplyAlpha(e,t,i,r,n=!1,a=!1,o=0,l=0,c=1,u=0,h=0,d=0,f=0,p,m){var P,M;const g=d!==0,_=p===void 0,[y,v]=this._getPipeline(r,g?Kp.InvertYPremultiplyAlphaWithOfst:Kp.InvertYPremultiplyAlpha,{invertY:n,premultiplyAlpha:a});o=Math.max(o,0),_&&(p=this._device.createCommandEncoder({})),(P=p.pushDebugGroup)==null||P.call(p,`internal process texture - invertY=${n} premultiplyAlpha=${a}`);let x;if(us.IsHardwareTexture(e)?(x=e.underlyingResource,n&&!a&&c===1&&o===0||(e=void 0)):(x=e,e=void 0),!x)return;g&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([u,h,d,f]),0,4*4);const A=e,b=(A==null?void 0:A._copyInvertYTempTexture)??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,21,void 0,"TempTextureForCopyWithInvertY"),C=(A==null?void 0:A._copyInvertYRenderPassDescr)??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${r}_${n?"InvertY":"DontInvertY"}_${a?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:b.createView({format:r,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},T=p.beginRenderPass(C);let w=g?A==null?void 0:A._copyInvertYBindGroupWithOfst:A==null?void 0:A._copyInvertYBindGroup;if(!w){const R={layout:v,entries:[{binding:0,resource:x.createView({format:r,dimension:"2d",baseMipLevel:l,mipLevelCount:1,arrayLayerCount:c,baseArrayLayer:o})}]};g&&R.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),w=this._device.createBindGroup(R)}T.setPipeline(y),T.setBindGroup(0,w),T.draw(4,1,0,0),T.end(),p.copyTextureToTexture({texture:b},{texture:x,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=b,A._copyInvertYRenderPassDescr=C,g?A._copyInvertYBindGroupWithOfst=w:A._copyInvertYBindGroup=w):this._deferredReleaseTextures.push([b,null]),(M=p.popDebugGroup)==null||M.call(p),_&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var u,h;const n=r===void 0,[a,o]=this._getPipeline(t,Kp.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});n&&(r=this._device.createCommandEncoder({})),(u=r.pushDebugGroup)==null||u.call(r,"internal copy texture with invertY");const l=r.beginRenderPass(i),c=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});l.setPipeline(a),l.setBindGroup(0,c),l.draw(4,1,0,0),l.end(),(h=r.popDebugGroup)==null||h.call(r),n&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,n=!1,a=!1,o="rgba8unorm",l=1,c,u=-1,h=0,d){l=us.GetSample(l);const f=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:f},m=O1[o]?16:0,g=us.IsCompressedFormat(o),_=t?us.ComputeNumMipmapLevels(e.width,e.height):1,y=u>=0?u:7;h|=t&&!g?1|m:0,!g&&!a&&(h|=m|2);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${a?"3D":"2D"}_${d?d+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${l}`,size:p,dimension:a?"3d":"2d",format:o,usage:y|h,sampleCount:l,mipLevelCount:_});return us.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,f,o,0,0,r,n,0,0),t&&i&&this.generateMipmaps(v,o,_,0,a,c)),v}createCubeTexture(e,t=!1,i=!1,r=!1,n=!1,a="rgba8unorm",o=1,l,c=-1,u=0,h){o=us.GetSample(o);const d=us.IsImageBitmapArray(e)?e[0].width:e.width,f=us.IsImageBitmapArray(e)?e[0].height:e.height,p=O1[a]?16:0,m=us.IsCompressedFormat(a),g=t?us.ComputeNumMipmapLevels(d,f):1,_=c>=0?c:7;u|=t&&!m?1|p:0,m||(u|=p|2);const y=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${h?h+"_":""}${d}x${f}x6_${t?"wmips":"womips"}_${a}_samples${o}`,size:{width:d,height:f,depthOrArrayLayers:6},dimension:"2d",format:a,usage:_|u,sampleCount:o,mipLevelCount:g});return us.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,y,d,f,a,r,n,0,0),t&&i&&this.generateCubeMipmaps(y,a,g,l)),y}generateCubeMipmaps(e,t,i,r){var a,o;const n=r===void 0;n&&(r=this._device.createCommandEncoder({})),(a=r.pushDebugGroup)==null||a.call(r,`create cube mipmaps - ${i} levels`);for(let l=0;l<6;++l)this.generateMipmaps(e,t,i,l,!1,r);(o=r.popDebugGroup)==null||o.call(r),n&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,n=!1,a){var d,f,p,m;const o=a===void 0,[l,c]=this._getPipeline(t);r=Math.max(r,0),o&&(a=this._device.createCommandEncoder({})),(d=a.pushDebugGroup)==null||d.call(a,`create mipmaps for face #${r} - ${i} levels`);let u;if(us.IsHardwareTexture(e)?(u=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(u=e,e=void 0),!u)return;const h=e;for(let g=1;gu;)this._device.queue.writeBuffer(a,t+h,i.buffer,o+h,u),h+=u;this._device.queue.writeBuffer(a,t+h,i.buffer,o+h,n-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const r=new Uint16Array(t);for(;e--;)i[e]=Im(r[e]);return i}readDataFromBuffer(e,t,i,r,n,a,o=0,l=0,c=null,u=!0,h=!1){const d=o===1?2:o===2?1:0,f=this._engine.uniqueId;return new Promise((p,m)=>{e.mapAsync(1,l,t).then(()=>{const g=e.getMappedRange(l,t);let _=c;if(h)_===null?_=cZ(o,t,!0,g):_=cZ(o,_.buffer,void 0,g);else if(_===null)switch(d){case 0:_=new Uint8Array(t),_.set(new Uint8Array(g));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g);break;case 2:_=new Float32Array(t/4),_.set(new Float32Array(g));break}else switch(d){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(g));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g,c);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(g));break}if(n!==a){d===1&&!h&&(n*=2,a*=2);const y=new Uint8Array(_.buffer);let v=n,x=0;for(let A=1;A{this._engine.isDisposed||this._engine.uniqueId!==f?p(new Uint8Array):m(g)})})}releaseBuffer(e){return mZ._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,e.references===0?(this._deferredReleaseBuffers.push(e.underlyingResource),!0):!1)}destroyDeferredBuffers(){for(let e=0;e1?4:1;return S4t[e.samplingMode]+E4t[(e._comparisonFunction||514)-512+1]+T4t[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,r,n,a,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i="linear",r="linear",n="nearest",l||(a=o=0);break;case 3:case 3:i="linear",r="linear",l?n="linear":(n="nearest",a=o=0);break;case 8:i="nearest",r="nearest",l?n="linear":(n="nearest",a=o=0);break;case 4:i="nearest",r="nearest",n="nearest",l||(a=o=0);break;case 5:i="nearest",r="linear",n="nearest",l||(a=o=0);break;case 6:i="nearest",r="linear",l?n="linear":(n="nearest",a=o=0);break;case 7:i="nearest",r="linear",n="nearest",a=o=0;break;case 1:case 1:i="nearest",r="nearest",n="nearest",a=o=0;break;case 9:i="linear",r="nearest",n="nearest",l||(a=o=0);break;case 10:i="linear",r="nearest",l?n="linear":(n="nearest",a=o=0);break;case 2:case 2:i="linear",r="linear",n="nearest",a=o=0;break;case 12:i="linear",r="nearest",n="nearest",a=o=0;break;default:i="nearest",r="nearest",n="nearest",a=o=0;break}return t>1&&(a!==0||o!==0)&&n!=="nearest"?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:n,lodMinClamp:a,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return"repeat";case 0:return"clamp-to-edge";case 2:return"mirror-repeat"}return"repeat"}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,r=this._GetSamplerFilterDescriptor(e,i);return{label:t,...r,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?By.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:r.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return"always";case 514:return"equal";case 516:return"greater";case 518:return"greater-equal";case 513:return"less";case 515:return"less-equal";case 512:return"never";case 517:return"not-equal";default:return"less"}}getSampler(e,t=!1,i=0,r){if(this.disabled)return this._device.createSampler(By._GetSamplerDescriptor(e,r));t?i=0:i===0&&(i=By.GetSamplerHashCode(e));let n=t?void 0:this._samplers[i];return n||(n=this._device.createSampler(By._GetSamplerDescriptor(e,r)),t||(this._samplers[i]=n)),n}}var qa;(function(s){s[s.StencilReadMask=0]="StencilReadMask",s[s.StencilWriteMask=1]="StencilWriteMask",s[s.DepthBias=2]="DepthBias",s[s.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",s[s.DepthStencilState=4]="DepthStencilState",s[s.MRTAttachments1=5]="MRTAttachments1",s[s.MRTAttachments2=6]="MRTAttachments2",s[s.RasterizationState=7]="RasterizationState",s[s.ColorStates=8]="ColorStates",s[s.ShaderStage=9]="ShaderStage",s[s.TextureStage=10]="TextureStage",s[s.VertexState=11]="VertexState",s[s.NumStates=12]="NumStates"})(qa||(qa={}));const cY={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},BI={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class Gn{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=["bgra8unorm"],this.setColorFormat("bgra8unorm"),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat("depth24plus-stencil8"),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i=us.GetSample(i),this.disabled){const a=Gn._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,a,i),Gn.NumCacheMiss++,Gn._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,Gn.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return Gn.NumCacheHitWithHash++,this._parameter.pipeline;const n=Gn._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,n,i),this._setRenderPipeline(this._parameter),Gn.NumCacheMiss++,Gn._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){Gn.NumPipelineCreationLastFrame=Gn._NumPipelineCreationCurrentFrame,Gn._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,n,a,o,l){this._depthWriteEnabled=o,this._depthTestEnabled=a,this._depthCompare=(l??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(n)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[qa.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[qa.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=O1[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let r=0,n=0,a=0;for(let o=0;o=32&&(n=0,r++)}this._mrtFormats.length=a,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[qa.MRTAttachments1]=i[0],this._states[qa.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=e===void 0?0:O1[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=e===null?1:BI[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:BI[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:BI[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[qa.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[qa.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,n,a,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:BI[i],this._stencilFrontPassOp=r===null?2:BI[r],this._stencilFrontFailOp=n===null?1:BI[n],this.setStencilReadMask(a),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return"triangle-list";case 2:return"point-list";case 1:return"line-list";case 3:return"point-list";case 4:return"line-list";case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return"line-strip";case 7:return"triangle-strip";case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return"triangle-list"}}static _GetAphaBlendOperation(e){switch(e){case 32774:return"add";case 32778:return"subtract";case 32779:return"reverse-subtract";case 32775:return"min";case 32776:return"max";default:return"add"}}static _GetAphaBlendFactor(e){switch(e){case 0:return"zero";case 1:return"one";case 768:return"src";case 769:return"one-minus-src";case 770:return"src-alpha";case 771:return"one-minus-src-alpha";case 772:return"dst-alpha";case 773:return"one-minus-dst-alpha";case 774:return"dst";case 775:return"one-minus-dst";case 776:return"src-alpha-saturated";case 32769:return"constant";case 32770:return"one-minus-constant";case 32771:return"constant";case 32772:return"one-minus-constant";default:return"one"}}static _GetCompareFunction(e){switch(e){case 0:return"never";case 1:return"less";case 2:return"equal";case 3:return"less-equal";case 4:return"greater";case 5:return"not-equal";case 6:return"greater-equal";case 7:return"always"}return"never"}static _GetStencilOpFunction(e){switch(e){case 0:return"zero";case 1:return"keep";case 2:return"replace";case 3:return"increment-clamp";case 4:return"decrement-clamp";case 5:return"invert";case 6:return"increment-wrap";case 7:return"decrement-wrap"}return"keep"}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,r=e.getSize();switch(t){case $.BYTE:switch(r){case 1:case 2:return i?"snorm8x2":"sint8x2";case 3:case 4:return i?"snorm8x4":"sint8x4"}break;case $.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?"unorm8x2":"uint8x2";case 3:case 4:return i?"unorm8x4":"uint8x4"}break;case $.SHORT:switch(r){case 1:case 2:return i?"snorm16x2":"sint16x2";case 3:case 4:return i?"snorm16x4":"sint16x4"}break;case $.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?"unorm16x2":"uint16x2";case 3:case 4:return i?"unorm16x4":"uint16x4"}break;case $.INT:switch(r){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case $.UNSIGNED_INT:switch(r){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case $.FLOAT:switch(r){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4"}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:Gn._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:Gn._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:Gn._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:Gn._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:Gn._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:Gn._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[qa.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,r=this._cullEnabled?this._cullFace:0,n=this._clampDepth?1:0,a=this._alphaToCoverageEnabled?1:0,o=i-1+(r<<1)+(n<<3)+(a<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[qa.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((this._alphaBlendFuncParams[0]===null?2:cY[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:cY[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:cY[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:cY[this._alphaBlendFuncParams[3]])<<12)+((this._alphaBlendEqParams[0]===null?1:this._alphaBlendEqParams[0]-32773)<<16)+((this._alphaBlendEqParams[1]===null?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[qa.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[qa.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,qa.DepthStencilState))}_setVertexState(e){var c;const t=this._statesLength;let i=qa.VertexState;const r=e._pipelineContext,n=r.shaderProcessingContext.attributeNamesFromEffect,a=r.shaderProcessingContext.attributeLocationsFromEffect;let o,l=0;for(let u=0;u0)for(let p=0;p=this._video.HAVE_CURRENT_DATA}dispose(){}}class hee{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=hee._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?By.GetSamplerHashCode(t):0;const n=r!==i.hashCode;n&&this.updateId++,this.isDirty||(this.isDirty=n)}setTexture(e,t){var a;let i=this.textures[e],r=-1;i?r=((a=i.texture)==null?void 0:a.uniqueId)??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,i.isExternalTexture=g1e.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const n=r!==((t==null?void 0:t.uniqueId)??-1);n&&this.updateId++,this.isDirty||(this.isDirty=n)}}hee._Counter=0;class Wz{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,Ds.CopyDst|Ds.Indirect|Ds.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Wz._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(t==null?void 0:t.uniqueId)!==((i=this.buffers[e])==null?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t===this._currentInstanceCount||!this.indirectDrawBuffer||!this._indirectDrawData||(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Wz._Counter=0;class gB{constructor(){this.values={}}}class Hs{static get Statistics(){return{totalCreated:Hs.NumBindGroupsCreatedTotal,lastFrameCreated:Hs.NumBindGroupsCreatedLastFrame,lookupLastFrame:Hs.NumBindGroupsLookupLastFrame,noLookupLastFrame:Hs.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Hs._Cache=new gB,Hs.NumBindGroupsCreatedTotal=0,Hs.NumBindGroupsCreatedLastFrame=0,Hs.NumBindGroupsLookupLastFrame=0,Hs.NumBindGroupsNoLookupLastFrame=0,Hs._NumBindGroupsCreatedCurrentFrame=0,Hs._NumBindGroupsLookupCurrentFrame=0,Hs._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Hs.NumBindGroupsCreatedLastFrame=Hs._NumBindGroupsCreatedCurrentFrame,Hs.NumBindGroupsLookupLastFrame=Hs._NumBindGroupsLookupCurrentFrame,Hs.NumBindGroupsNoLookupLastFrame=Hs._NumBindGroupsNoLookupCurrentFrame,Hs._NumBindGroupsCreatedCurrentFrame=0,Hs._NumBindGroupsLookupCurrentFrame=0,Hs._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var l,c,u,h,d,f;let r,n=Hs._Cache;const a=this.disabled||i.forceBindGroupCreation;if(!a){if(!t.isDirty(i.updateId)&&!i.isDirty)return Hs._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const p of e.shaderProcessingContext.bufferNames){const m=((l=t.buffers[p])==null?void 0:l.uniqueId)??0;let g=n.values[m];g||(g=new gB,n.values[m]=g),n=g}for(const p of e.shaderProcessingContext.samplerNames){const m=((c=i.samplers[p])==null?void 0:c.hashCode)??0;let g=n.values[m];g||(g=new gB,n.values[m]=g),n=g}for(const p of e.shaderProcessingContext.textureNames){const m=((h=(u=i.textures[p])==null?void 0:u.texture)==null?void 0:h.uniqueId)??0;let g=n.values[m];g||(g=new gB,n.values[m]=g),n=g}r=n.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,r)return t.bindGroups=r,Hs._NumBindGroupsLookupCurrentFrame++,r;r=[],t.bindGroups=r,a||(n.bindGroups=r),Hs.NumBindGroupsCreatedTotal++,Hs._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let p=0;pT==="texture"?"":w)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}g[y].resource=this._cacheSampler.getSampler(C,!1,b.hashCode,C.label)}else fe.Error(`Sampler "${A}" could not be bound. entry=${JSON.stringify(v)}, materialContext=${JSON.stringify(i,(C,T)=>C==="texture"||C==="sampler"?"":T)}`,50)}else if(v.texture||v.storageTexture){const b=i.textures[A];if(b){if(this._engine.dbgSanityChecks&&b.texture===null){fe.Error(`Trying to bind a null texture! entry=${JSON.stringify(v)}, bindingInfo=${JSON.stringify(b,(T,w)=>T==="texture"?"":w)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const C=b.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!C||v.texture&&!C.view||v.storageTexture&&!C.viewForWriting)){fe.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(v)}, name=${A}, bindingInfo=${JSON.stringify(b,(T,w)=>T==="texture"?"":w)}, isReady=${(d=b.texture)==null?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}g[y].resource=v.storageTexture?C.viewForWriting:C.view}else fe.Error(`Texture "${A}" could not be bound. entry=${JSON.stringify(v)}, materialContext=${JSON.stringify(i,(C,T)=>C==="texture"||C==="sampler"?"":T)}`,50)}else if(v.externalTexture){const b=i.textures[A];if(b){if(this._engine.dbgSanityChecks&&b.texture===null){fe.Error(`Trying to bind a null external texture! entry=${JSON.stringify(v)}, name=${A}, bindingInfo=${JSON.stringify(b,(T,w)=>T==="texture"?"":w)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const C=b.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!C){fe.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(v)}, name=${A}, bindingInfo=${JSON.stringify(b,(T,w)=>T==="texture"?"":w)}, isReady=${(f=b.texture)==null?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}g[y].resource=this._device.importExternalTexture({source:C})}else fe.Error(`Texture "${A}" could not be bound. entry=${JSON.stringify(v)}, materialContext=${JSON.stringify(i,(C,T)=>C==="texture"||C==="sampler"?"":T)}`,50)}else if(v.buffer){const b=t.buffers[A];if(b){const C=b.underlyingResource;g[y].resource.buffer=C,g[y].resource.size=b.capacity}else fe.Error(`Can't find buffer "${A}". entry=${JSON.stringify(v)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const _=o[p];r[p]=this._device.createBindGroup({layout:_,entries:g})}return r}}Hs.NumBindGroupsCreatedTotal=0;Hs.NumBindGroupsCreatedLastFrame=0;Hs.NumBindGroupsLookupLastFrame=0;Hs.NumBindGroupsNoLookupLastFrame=0;Hs._Cache=new gB;Hs._NumBindGroupsCreatedCurrentFrame=0;Hs._NumBindGroupsLookupCurrentFrame=0;Hs._NumBindGroupsNoLookupCurrentFrame=0;const I4t="clearQuadVertexShader",P4t=`uniform depthValue: f32;const pos=array( vec2f(-1.0,1.0), vec2f(1.0,1.0), vec2f(-1.0,-1.0), vec2f(1.0,-1.0) ); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0); #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStoreWGSL[I4t]=P4t;const w4t="clearQuadPixelShader",D4t=`uniform color: vec4f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;} `;de.ShadersStoreWGSL[w4t]=D4t;class L4t{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new e0(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,1)}clear(e,t,i,r,n=1){let a,o=null,l;const c=!!this._engine._currentRenderTarget;if(e)a=e;else{let g=0;this._keyTemp.length=0;for(let y=0;y1?2**36:0)+_*2**37,l=this._keyTemp.join("_"),o=this._bundleCache[l],o)return o;a=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:us.GetSample(n)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&us.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const u=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,n),h=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),h.uniformBuffer.update();const d=c?this._engine._ubInvertY:this._engine._ubDontInvertY,f=h.uniformBuffer.getBuffer(),p=f.uniqueId+"-"+d.uniqueId;let m=this._bindGroups[p];if(!m){const g=h.bindGroupLayouts[0];m=this._bindGroups[p]=[],m.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${p}`,layout:g[0],entries:[]})),Kd._SimplifiedKnownBindings||m.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${p}`,layout:g[1],entries:[]})),m.push(this._device.createBindGroup({label:`clearQuadBindGroup${Kd._SimplifiedKnownBindings?1:2}-${p}`,layout:g[Kd._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:d.underlyingResource,size:d.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}a.setPipeline(u);for(let g=0;g{const n=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,n},n=>{if(this._engine.isDisposed||this._engine.uniqueId!==r)return null;throw n})}async readValue(e=0){const t=this._getBuffer(e,1);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then(()=>{const r=new BigUint64Array(t.getMappedRange()),n=Number(r[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n},r=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw r})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then(()=>{const r=new BigUint64Array(t.getMappedRange()),n=Number(r[1]-r[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n},r=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw r})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(r=>{t._addDuration(i,r!==null&&r>0?r:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class N4t{constructor(e,t,i,r=2,n){this._count=r,this._querySet=new Xke(e,r,"timestamp",t,i,!0,n)}start(e){var t;(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class F4t{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet!==void 0;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,n=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=n,this._allocateNewIndices(r)}createQuery(){this._availableIndices.length===0&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;(e=this._querySet)==null||e.dispose(),this._availableIndices.length=0}}class Yh{async initTwgsl(e){if(!Yh._Twgsl)return e=e||{},e={...Yh._TWgslDefaultOptions,...e},e.twgsl?(Yh._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Me.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Yh._Twgsl=await self.twgsl(Me.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Yh._Twgsl.convertSpirV2WGSL(e,Yh.DisableUniformityAnalysis||t);return Yh.ShowWGSLShaderCode&&(fe.Log(i),fe.Log("***********************************************")),Yh.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); `+i:i}}Yh._TWgslDefaultOptions={jsPath:`${Me._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Me._DefaultCdnUrl}/twgsl/twgsl.wasm`};Yh.ShowWGSLShaderCode=!1;Yh.DisableUniformityAnalysis=!1;Yh._Twgsl=null;class B4t{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),this._mode===1&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}class k4t extends g1e{constructor(e){super(e)}}const ZTe={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},qTe={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},U4t=new Ze;class Oi extends Ge{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return this._cacheSampler?this._cacheSampler.disabled:!1}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return this._cacheRenderPipeline?this._cacheRenderPipeline.disabled:!1}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return this._cacheBindGroups?this._cacheBindGroups.disabled:!1}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Bge(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return fe.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new $ge:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Oi(e,t);return new Promise(r=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>r(i))})}constructor(e,t={}){if(super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._glslangAndTintAreFullyLoaded=!1,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._snapshotRenderingMode=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._workingGlslangAndTintPromise=null,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Oge,this._name="WebGPU",this._drawCalls=new io,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,fe.Log(`Babylon.js v${Ge.Version} - ${this.description} engine`),!navigator.gpu){fe.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new e4t,this._shaderProcessorWGSL=new d4t}prepareGlslangAndTintAsync(){return this._workingGlslangAndTintPromise||(this._workingGlslangAndTintPromise=new Promise(e=>{var t;this._initGlslang(this._glslangOptions??((t=this._options)==null?void 0:t.glslangOptions)).then(i=>{var r;this._glslang=i,this._tintWASM=new Yh,this._tintWASM.initTwgsl(this._twgslOptions??((r=this._options)==null?void 0:r.twgslOptions)).then(()=>{this._glslangAndTintAreFullyLoaded=!0,e()})})})),this._workingGlslangAndTintPromise}initAsync(e,t){return this.uniqueId=Oi._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,navigator.gpu.requestAdapter(this._options).then(i=>{var r;if(i){this._adapter=i,this._adapterSupportedExtensions=[],(r=this._adapter.features)==null||r.forEach(o=>this._adapterSupportedExtensions.push(o)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(o=>{this._adapterInfo=o});const n=this._options.deviceDescriptor??{},a=(n==null?void 0:n.requiredFeatures)??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(a){const o=a,l=[];for(const c of o)this._adapterSupportedExtensions.indexOf(c)!==-1&&l.push(c);n.requiredFeatures=l}if(this._options.setMaximumLimits&&!n.requiredLimits){n.requiredLimits={};for(const o in this._adapterSupportedLimits)o==="minSubgroupSize"||o==="maxSubgroupSize"||(n.requiredLimits[o]=this._adapterSupportedLimits[o])}return n.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(n)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(i=>{var n,a;this._device=i,this._deviceEnabledExtensions=[],(n=this._device.features)==null||n.forEach(o=>this._deviceEnabledExtensions.push(o)),this._deviceLimits=i.limits;let r=-1;this._device.addEventListener("uncapturederror",o=>{++r{this._isDisposed||(this._contextWasLost=!0,fe.Warn("WebGPU context lost. "+o),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var p,m;const l=this.snapshotRenderingMode,c=this.snapshotRendering,u=this.disableCacheSamplers,h=this.disableCacheRenderPipelines,d=this.disableCacheBindGroups,f=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??((p=this._options)==null?void 0:p.glslangOptions),this._twgslOptions??((m=this._options)==null?void 0:m.twgslOptions)),this.snapshotRenderingMode=l,this.snapshotRendering=c,this.disableCacheSamplers=u,this.disableCacheRenderPipelines=h,this.disableCacheBindGroups=d,this.enableGPUTimingMeasurements=f,this._currentRenderPass=null}))})}).then(()=>{this._initializeLimits(),this._bufferManager=new mZ(this,this._device),this._textureHelper=new C4t(this,this._device,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new By(this._device),this._cacheBindGroups=new Hs(this._device,this._cacheSampler,this),this._timestampQuery=new O4t(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new F4t(this,this._device,this._bufferManager):void 0,this._bundleList=new C1e(this._device),this._snapshotRendering=new B4t(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Ds.Uniform|Ds.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Ds.Uniform|Ds.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,fe.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._emptyVertexBuffer=new $(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new e0(this._device,this._emptyVertexBuffer),this._depthCullingState=new R4t(this._cacheRenderPipeline),this._stencilStateComposer=new M4t(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new L4t(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(i=>{throw fe.Error("A fatal error occurred during WebGPU creation/initialization."),i})}_initGlslang(e){return e=e||{},e={...Oi._GlslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Me.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(Me.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage*2,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf("texture-compression-astc")>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf("texture-compression-etc2")>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable")>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf("float32-filterable")>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:typeof BigUint64Array<"u"&&this._deviceEnabledExtensions.indexOf("timestamp-query")!==-1?!0:void 0,supportOcclusionQuery:typeof BigUint64Array<"u",canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new XQ],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e);let t;if(this._options.antialias){const n={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._options.swapChainFormat,usage:16};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(n),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ze(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new Ze(0,0,0,1),loadOp:"clear",storeOp:"store"}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?"depth24plus-stencil8":"depth32float",this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._mainRenderPassWrapper.depthTextureFormat,usage:16};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:"2d",format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:"clear",depthStoreOp:"store",stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?"clear":void 0,stencilStoreOp:this.isStencilEnable?"store":void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:r}}_sharedInit(e){super._sharedInit(e),Nge(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:17,alphaMode:this.premultipliedAlpha?"premultiplied":"opaque"})}resizeImageBitmap(e,t,i){return Uge(this,e,t,i)}_createImageBitmapFromSource(e,t){return kge(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&zge(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Vge()}enterPointerlock(){this._renderingCanvas&&VJ(this._renderingCanvas)}exitPointerlock(){Gge()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){e0.ResetCache(),Hs.ResetCache();const t=r=>{var n;for(const a of r){for(const o of a.meshes){const l=o.subMeshes;if(l)for(const c of l)c._drawWrappers=[]}for(const o of a.materials)(n=o._materialContext)==null||n.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const r of this._uniformBuffers)r.name.indexOf("leftOver")<0&&i.push(r);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,a=i===0?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===0?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(a,o,i,r,n)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,a=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o=`#version 450 `,l=r===0?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),c=r===0?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),u=this._createPipelineStageDescriptor(l,c,r,n,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),u}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new xv(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Z3t(e,this)}createMaterialContext(){return new hee}createDrawContext(){return new Wz(this._bufferManager)}async _preparePipelineContext(e,t,i,r,n,a,o,l,c,u,h){const d=e,f=d.shaderProcessingContext.shaderLanguage;f===0&&!this._glslangAndTintAreFullyLoaded&&await this.prepareGlslangAndTintAsync(),this.dbgShowShaderCode&&(fe.Log(["defines",l]),fe.Log(t),fe.Log(i),fe.Log("***********************************************")),d.sources={fragment:i,vertex:t,rawVertex:n,rawFragment:a},r?d.stages=this._compileRawPipelineStageDescriptor(t,i,f):d.stages=this._compilePipelineStageDescriptor(t,i,l,f),h()}getAttributes(e,t){const i=new Array(t.length),r=e;for(let n=0;n0,a.is3D=c>0,a._cachedWrapU=0,a._cachedWrapV=0,a._useSRGBBuffer=n.useSRGBBuffer,a.label=n.label,this._internalTexturesCache.push(a),i||this._textureHelper.createGPUTextureForInternalTexture(a,o,l,u||1,n.creationFlags),a}createTexture(e,t,i,r,n=3,a=null,o=null,l=null,c=null,u=null,h=null,d,f,p,m){return this._createTextureBase(e,t,i,r,n,a,o,(g,_,y,v,x,A,b,C)=>{var w;const T=v;if(g.baseWidth=T.width,g.baseHeight=T.height,g.width=T.width,g.height=T.height,g.format=g.format!==-1?g.format:u??5,g.type=g.type!==-1?g.type:0,g._creationFlags=p??0,C(g.width,g.height,T,_,g,()=>{}),(w=g._hardwareTexture)!=null&&w.underlyingResource)!A&&!b&&this._generateMipmaps(g,this._uploadEncoder);else{const P=this._textureHelper.createGPUTextureForInternalTexture(g,T.width,T.height,void 0,p);us.IsImageBitmap(T)&&(this._textureHelper.updateTexture(T,g,T.width,T.height,g.depth,P.format,0,0,x,!1,0,0),!A&&!b&&this._generateMipmaps(g,this._uploadEncoder))}y&&y.removePendingData(g),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>!1,l,c,u,h,d,f,m)}wrapWebGPUTexture(e){const t=new XQ(e),i=new zr(this,0,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;const n=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,n)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),n&&n.autoBindSampler){const a=i+"Sampler";this._currentMaterialContext.setSampler(a,t)}}}createPrefilteredCubeTexture(e,t,i,r,n=null,a=null,o,l=null,c=!0){const u=h=>{if(!h){n&&n(null);return}const d=h.texture;c?h.info.sphericalPolynomial&&(d._sphericalPolynomial=h.info.sphericalPolynomial):d._sphericalPolynomial=new hg,d._source=9,n&&n(d)};return this.createCubeTexture(e,t,null,!1,u,a,o,l,c,i,r)}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let n=0;n{const o=()=>{e.mapAsync(1,0,t).then(()=>{const l=e.getMappedRange(0,t);let c=i;if(c===void 0)c=new Uint8Array(t),c.set(new Uint8Array(l));else{const u=c.constructor;c=new u(c.buffer),c.set(new u(l))}e.unmap(),this._bufferManager.releaseBuffer(e),n(c)},l=>{this.isDisposed?n(new Uint8Array):a(l)})};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce(()=>{o()})})}readFromStorageBuffer(e,t,i,r,n){i=i||e.capacity;const a=this._bufferManager.createRawBuffer(i,Ds.MapRead|Ds.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,a,0,i),this._readFromGPUBuffer(a,i,r,n)}readFromMultipleStorageBuffers(e,t,i,r,n){i=i||e[0].capacity;const a=this._bufferManager.createRawBuffer(i*e.length,Ds.MapRead|Ds.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let o=0;o0;for(const n in e){const a=e[n],o=i[n],l=o.group,c=o.binding,u=a.type,h=a.object;let d=a.indexInGroupEntries,f=this._bindGroupEntries[l];switch(f||(f=this._bindGroupEntries[l]=[]),u){case 5:{const p=h;d!==void 0&&r?f[d].resource=this._cacheSampler.getSampler(p):(a.indexInGroupEntries=f.length,f.push({binding:c,resource:this._cacheSampler.getSampler(p)}));break}case 0:case 4:{const p=h,m=p._texture._hardwareTexture;d!==void 0&&r?(u===0&&(f[d++].resource=this._cacheSampler.getSampler(p._texture)),f[d].resource=m.view):(a.indexInGroupEntries=f.length,u===0&&f.push({binding:c-1,resource:this._cacheSampler.getSampler(p._texture)}),f.push({binding:c,resource:m.view}));break}case 1:{const p=h,m=p._texture._hardwareTexture;m.textureAdditionalUsages&8||fe.Error(`computeDispatch: The texture (name=${p.name}, uniqueId=${p.uniqueId}) is not a storage texture!`,50),d!==void 0&&r?f[d].resource=m.viewForWriting:(a.indexInGroupEntries=f.length,f.push({binding:c,resource:m.viewForWriting}));break}case 6:{const m=h.underlyingResource;d!==void 0&&r?f[d].resource=this._device.importExternalTexture({source:m}):(a.indexInGroupEntries=f.length,f.push({binding:c,resource:this._device.importExternalTexture({source:m})}));break}case 2:case 3:case 7:{const p=u===7?h:h.getBuffer(),m=p.underlyingResource;d!==void 0&&r?(f[d].resource.buffer=m,f[d].resource.size=p.capacity):(a.indexInGroupEntries=f.length,f.push({binding:c,resource:{buffer:m,offset:0,size:p.capacity}}));break}}}for(let n=0;n0&&d.dispatchWorkgroups(i,r,n),d.end(),c&&(this._timestampQuery.endPass(this._timestampIndex,c),this._timestampIndex+=2)};Oi.prototype.releaseComputeEffects=function(){for(const s in this._compiledComputeEffects){const e=this._compiledComputeEffects[s].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};Oi.prototype._prepareComputePipelineContext=function(s,e,t,i,r){const n=s;this.dbgShowShaderCode&&(fe.Log(i),fe.Log(e)),n.sources={compute:e,rawCompute:t},n.stage=this._createComputePipelineStageDescriptor(e,i,r)};Oi.prototype._releaseComputeEffect=function(s){this._compiledComputeEffects[s._key]&&(delete this._compiledComputeEffects[s._key],this._deleteComputePipelineContext(s.getPipelineContext()))};Oi.prototype._rebuildComputeEffects=function(){for(const s in this._compiledComputeEffects){const e=this._compiledComputeEffects[s];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};Oi.prototype._executeWhenComputeStateIsCompiled=function(s,e){s.stage.module.getCompilationInfo().then(t=>{const i={numErrors:0,messages:[]};for(const r of t.messages)r.type==="error"&&i.numErrors++,i.messages.push({type:r.type,text:r.message,line:r.lineNum,column:r.linePos,length:r.length,offset:r.offset});e(i)})};Oi.prototype._deleteComputePipelineContext=function(s){s&&s.dispose()};Oi.prototype._createComputePipelineStageDescriptor=function(s,e,t){return e?e="//"+e.split(` `).join(` //`)+` `:e="",{module:this._device.createShaderModule({code:e+s}),entryPoint:t}};Oi.prototype._createDepthStencilCubeTexture=function(s,e){const t=new zr(this,e.generateStencil?12:14);t.isCube=!0,t.label=e.label;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:e.generateStencil?13:14,...e};t.format=i.depthTextureFormat,this._setupDepthStencilTexture(t,s,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const r=t._hardwareTexture;return t.type=us.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(t),t};Oi.prototype.createCubeTexture=function(s,e,t,i,r=null,n=null,a,o=null,l=!1,c=0,u=0,h=null,d,f=!1,p=null){return this.createCubeTextureBase(s,e,t,!!i,r,n,a,o,l,c,u,h,null,(m,g)=>{const _=g,y=_[0].width,v=y;this._setCubeMapTextureParams(m,!i),m.format=a??-1;const x=this._textureHelper.createGPUTextureForInternalTexture(m,y,v);this._textureHelper.updateCubeTextures(_,x.underlyingResource,y,v,x.format,!1,!1,0,0),i||this._generateMipmaps(m,this._uploadEncoder),m.isReady=!0,m.onLoadedObservable.notifyObservers(m),m.onLoadedObservable.clear(),r&&r()},!!f,p)};Oi.prototype._setCubeMapTextureParams=function(s,e,t){s.samplingMode=e?3:2,s._cachedWrapU=0,s._cachedWrapV=0,t&&(s._maxLodLevel=t)};Oi.prototype.generateMipMapsForCubemap=function(s){var e;s.generateMipMaps&&((e=s._hardwareTexture)!=null&&e.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(s),this._generateMipmaps(s))};Oi.prototype._debugPushGroup=function(s,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(s):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(s):this._pendingDebugCommands.push(["push",s]))};Oi.prototype._debugPopGroup=function(s){this._options.enableGPUDebugMarkers&&(s===0||s===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};Oi.prototype._debugInsertMarker=function(s,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(s):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(s):this._pendingDebugCommands.push(["insert",s]))};Oi.prototype._debugFlushPendingCommands=function(){for(let s=0;s{e==null||e.removePendingData(d),c&&m&&c(m.status+" "+m.statusText,g)},p=m=>{const g=d.width,_=a(m);if(_){if(o){const y=i===4,v=o(_),x=d._hardwareTexture,A=[0,1,2,3,4,5];for(let b=0;b>b,T=[];for(let w=0;w<6;w++){let P=v[b][A[w]];y&&(P=Kz(P,C,C,r)),T.push(new Uint8Array(P.buffer,P.byteOffset,P.byteLength))}this._textureHelper.updateCubeTextures(T,x.underlyingResource,C,C,x.format,h,!1,0,0)}}else this.updateRawCubeTexture(d,_,i,r,h);d.isReady=!0,e==null||e.removePendingData(d),l&&l()}};return this._loadFile(s,m=>{p(m)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};Oi.prototype.createRawTexture3D=function(s,e,t,i,r,n,a,o,l=null,c=0,u=0){const d=new zr(this,10);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=r,d.type=c,d.generateMipMaps=n,d.samplingMode=o,d.is3D=!0,d._creationFlags=u,this._doNotHandleContextLost||(d._bufferView=s),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,u),this.updateRawTexture3D(d,s,r,a,l,c),this._internalTexturesCache.push(d),d};Oi.prototype.updateRawTexture3D=function(s,e,t,i,r=null,n=0){if(this._doNotHandleContextLost||(s._bufferView=e,s.format=t,s.invertY=i,s._compression=r),e){const a=s._hardwareTexture;t===4&&(e=Kz(e,s.width,s.height,n));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,s,s.width,s.height,s.depth,a.format,0,0,i,!1,0,0),s.generateMipMaps&&this._generateMipmaps(s,this._uploadEncoder)}s.isReady=!0};Oi.prototype.createRawTexture2DArray=function(s,e,t,i,r,n,a,o,l=null,c=0,u=0){const d=new zr(this,11);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=r,d.type=c,d.generateMipMaps=n,d.samplingMode=o,d.is2DArray=!0,d._creationFlags=u,this._doNotHandleContextLost||(d._bufferView=s),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,u),this.updateRawTexture2DArray(d,s,r,a,l,c),this._internalTexturesCache.push(d),d};Oi.prototype.updateRawTexture2DArray=function(s,e,t,i,r=null,n=0){if(this._doNotHandleContextLost||(s._bufferView=e,s.format=t,s.invertY=i,s._compression=r),e){const a=s._hardwareTexture;t===4&&(e=Kz(e,s.width,s.height,n));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,s,s.width,s.height,s.depth,a.format,0,0,i,!1,0,0),s.generateMipMaps&&this._generateMipmaps(s,this._uploadEncoder)}s.isReady=!0};function Kz(s,e,t,i){let r,n=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),n=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a0,s.is3D=c>0,s.depth=l||c,s.isReady=!0,s.samples=n,s.generateMipMaps=!1,s.samplingMode=i?2:1,s.type=1,s._comparisonFunction=r,s._cachedWrapU=0,s._cachedWrapV=0};Oi.prototype.updateRenderTargetTextureSampleCount=function(s,e){return!s||!s.texture||s.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(s.texture,e),s._depthStencilTexture&&(this._textureHelper.createMSAATexture(s._depthStencilTexture,e),s._depthStencilTexture.samples=e),s._samples=e,s.texture.samples=e),e};Oi.prototype.createRenderTargetCubeTexture=function(s,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,s),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,t.label=i.label??"RenderTargetWrapper",t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer;const r=new zr(this,5);return r.width=s,r.height=s,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=i.samples,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,this._internalTexturesCache.push(r),t.setTextures(r),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,i.samplingMode===void 0||i.samplingMode===2||i.samplingMode===2||i.samplingMode===3||i.samplingMode===3||i.samplingMode===5||i.samplingMode===6||i.samplingMode===7||i.samplingMode===11,t._generateStencilBuffer,t.samples),e&&e.createMipMaps&&!i.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),e&&e.createMipMaps&&!i.generateMipMaps&&(r.generateMipMaps=!1),t};Oi.prototype.setDepthStencilTexture=function(s,e,t,i){!t||!t.depthStencilTexture?this._setTexture(s,null,void 0,void 0,i):this._setTexture(s,t,!1,!0,i)};function V4t(s){return!!(s&&s.underlyingResource!==void 0)}Oi.prototype.updateVideoTexture=function(s,e,t){var r;if(!s||s._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let i=s._hardwareTexture;if((r=s._hardwareTexture)!=null&&r.underlyingResource||(i=this._textureHelper.createGPUTextureForInternalTexture(s)),V4t(e)){if(e.isReady()){try{this._textureHelper.copyVideoToTexture(e,s,i.format,!t),s.generateMipMaps&&this._generateMipmaps(s)}catch{}s.isReady=!0}}else e&&this.createImageBitmap(e).then(n=>{this._textureHelper.updateTexture(n,s,s.width,s.height,s.depth,i.format,0,0,!t,!1,0,0),s.generateMipMaps&&this._generateMipmaps(s),s.isReady=!0}).catch(()=>{s.isReady=!0})};class G4t{static async CreateAsync(e,t){return await Oi.IsSupportedAsync?Oi.CreateAsync(e,t):vt.IsSupported?new vt(e,void 0,t):new Tke(t)}}class Zf{}Zf.COPY=1;Zf.CUT=2;Zf.PASTE=3;class YQ{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return Zf.COPY;case 86:return Zf.PASTE;case 88:return Zf.CUT;default:return-1}}}class kf extends jn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Re.Gray(),i=is.DefaultUtilityLayer,r=null,n=1,a=Re.Yellow(),o=Re.Gray()){var A,b,C,T,w,P,M;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new D(0,0,0),this._incrementalStartupValue=D.Zero(),this._parent=r,this._coloredMaterial=new et("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Re(.1,.1,.1)),this._hoverMaterial=new et("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._disableMaterial=new et("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Ee("axis",i.utilityLayerScene);const{arrowMesh:l,arrowTail:c}=this._createGizmoMesh(this._gizmoMesh,n),u=this._createGizmoMesh(this._gizmoMesh,n+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,jn.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const h=l.position.clone(),d=c.position.clone(),f=c.scaling.clone(),p=R=>{const I=R*(3/this._rootMesh.scaling.length())*6;l.position.z+=I/3.5,c.scaling.y+=I,this.dragScale=c.scaling.y,c.position.z=l.position.z/2},m=()=>{l.position.set(h.x,h.y,h.z),c.position.set(d.x,d.y,d.z),c.scaling.set(f.x,f.y,f.z),this.dragScale=c.scaling.y,this._dragging=!1};this.dragBehavior=new sl({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let g=0,_=0;const y={snapDistance:0};this.dragBehavior.onDragObservable.add(R=>{if(this.attachedNode){const I=this.sensitivity*R.dragDistance*(this.scaleRatio*3/this._rootMesh.scaling.length()),L=this._tmpVector;let k=!1,V=0;if(this.uniformScaling?L.setAll(.57735):L.copyFrom(e),this.snapDistance==0)L.scaleToRef(I,L);else{g+=I,_+=I;const z=this.incrementalSnap?_:g;Math.abs(z)>this.snapDistance?(V=Math.floor(Math.abs(z)/this.snapDistance),z<0&&(V*=-1),g=g%this.snapDistance,L.scaleToRef(this.snapDistance*V,L),k=!0):L.scaleInPlace(0)}L.addInPlaceFromFloats(1,1,1),L.x=Math.abs(L.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,se.Quaternion[0],se.Vector3[2],jn.PreserveScaling?H:void 0),L.addInPlace(this._incrementalStartupValue),L.addInPlaceFromFloats(-1,-1,-1),L.x=Math.abs(L.x)*(this._incrementalStartupValue.x>0?1:-1),L.y=Math.abs(L.y)*(this._incrementalStartupValue.y>0?1:-1),L.z=Math.abs(L.z)*(this._incrementalStartupValue.z>0?1:-1),he.ComposeToRef(L,se.Quaternion[0],se.Vector3[2],se.Matrix[1])):(he.ScalingToRef(L.x,L.y,L.z,se.Matrix[2]),se.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),se.Matrix[1])),se.Matrix[1].decompose(se.Vector3[1],void 0,void 0,jn.PreserveScaling?H:void 0);const j=1e5;Math.abs(se.Vector3[1].x){var I;this._dragging=!0;const R=this.attachedNode._isMesh?this.attachedNode:void 0;(I=this.attachedNode)==null||I.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,jn.PreserveScaling?R:void 0),g=0,_=0}),this.dragBehavior.onDragObservable.add(R=>p(R.dragDistance)),this.dragBehavior.onDragEndObservable.add(m),(C=(b=(A=r==null?void 0:r.uniformScaleGizmo)==null?void 0:A.dragBehavior)==null?void 0:b.onDragObservable)==null||C.add(R=>p(R.delta.y)),(P=(w=(T=r==null?void 0:r.uniformScaleGizmo)==null?void 0:T.dragBehavior)==null?void 0:w.onDragEndObservable)==null||P.add(m);const v={gizmoMeshes:[l,c],colliderMeshes:[u.arrowMesh,u.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(M=this._parent)==null||M.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(R=>{var L,k,V,H;if(this._customMeshSet)return;let I=(L=this._parent)==null?void 0:L.getAxisCache(this._gizmoMesh);if(this._isHovered=!!I&&I.colliderMeshes.indexOf((k=R==null?void 0:R.pickInfo)==null?void 0:k.pickedMesh)!=-1,I=(V=this._parent)==null?void 0:V.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!!I&&I.colliderMeshes.indexOf((H=R==null?void 0:R.pickInfo)==null?void 0:H.pickedMesh)!=-1),!this._parent){const j=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,j)}}),this.dragBehavior.onEnabledObservable.add(R=>{this._setGizmoMeshMaterial(v.gizmoMeshes,R?this._coloredMaterial:this._disableMaterial)});const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const r=ph("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),n=ou("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,n.material=this._coloredMaterial,n.position.z+=.275/2,n.rotation.x=Math.PI/2,i&&(r.visibility=0,n.visibility=0),e.addChild(r),e.addChild(n),{arrowMesh:r,arrowTail:n}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach(i=>{i.material=this._coloredMaterial,i.color&&(i.color=this._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)}}kf.MinimumAbsoluteScale=ci;class S1e extends jn{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let r=0;r<3;r++)for(let n=0;n<3;n++)for(let a=0;a<3;a++){const o=(r===1?1:0)+(n===1?1:0)+(a===1?1:0);if(!(o===1||o===3)){if(t[i]){const l=new D(r-1,n-1,a-1);l.multiplyInPlace(this._axisFactor),t[i].setEnabled(l.lengthSquared()>ci)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Re(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(t=>{t.color&&(t.color=e)})}constructor(e=Re.Gray(),t=is.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new D(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateAnchorsDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new Pe,this._tmpVector=new D(0,0,0),this._tmpRotationMatrix=new he,this._incrementalStartupValue=D.Zero(),this._incrementalAnchorStartupValue=D.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new Ae,this.onScaleBoxDragObservable=new Ae,this.onScaleBoxDragEndObservable=new Ae,this.onRotationSphereDragObservable=new Ae,this.onRotationSphereDragEndObservable=new Ae,this.scalePivot=null,this._axisFactor=new D(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new D,this._dragMesh=null,this._pointerDragBehavior=new sl,this._cornerMesh=null,this.updateScale=!1,this._anchorMesh=new _t("anchor",t.utilityLayerScene),this._coloredMaterial=new et("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new et("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new _t("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new Pe;const i=[];i.push(dn("lines",{points:[new D(0,0,0),new D(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(0,0,0),new D(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(0,0,0),new D(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(this._boundingDimensions.x,0,0),new D(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(this._boundingDimensions.x,0,0),new D(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(0,this._boundingDimensions.y,0),new D(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(0,this._boundingDimensions.y,0),new D(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(0,0,this._boundingDimensions.z),new D(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(0,0,this._boundingDimensions.z),new D(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new D(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new D(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(dn("lines",{points:[new D(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new D(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach(n=>{n.color=e,n.position.addInPlace(new D(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),n.isPickable=!1,this._lineBoundingBox.addChild(n)}),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateAnchorsParent=new _t("",t.utilityLayerScene),this._rotateAnchorsParent.rotationQuaternion=new Pe;for(let n=0;n<12;n++){const a=ph("",{width:.4,height:.4,depth:1.6},t.utilityLayerScene);a.rotationQuaternion=new Pe,a.material=this._coloredMaterial,a.isNearGrabbable=!0;const o=new sl({});o.moveAttached=!1,o.updateDragPlane=!1,a.addBehavior(o);const l=new D(1,0,0);let c=0,u=0;o.onDragStartObservable.add(()=>{l.copyFrom(a.forward),c=0,u=0}),o.onDragObservable.add(h=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const d=this.attachedMesh.parent;if(d&&d.scaling&&d.scaling.isNonUniformWithinEpsilon(.001)){fe.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}ds._RemoveAndStorePivotPoint(this.attachedMesh);const f=l,p=h.dragPlaneNormal.scale(D.Dot(h.dragPlaneNormal,f)),m=f.subtract(p).normalizeToNew();let g=D.Dot(m,h.delta)<0?Math.abs(h.delta.length()):-Math.abs(h.delta.length());if(g=g/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=Pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=Pe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),c+=g,Math.abs(c)<=2*Math.PI){if(this.rotationSnapDistance>0){const _=Math.floor(Math.abs(c)/this.rotationSnapDistance)*(c<0?-1:1),y=this.rotationSnapDistance*_;g=y-u,u=y}n>=8?Pe.RotationYawPitchRollToRef(0,0,g,this._tmpQuaternion):n>=4?Pe.RotationYawPitchRollToRef(g,0,0,this._tmpQuaternion):Pe.RotationYawPitchRollToRef(0,g,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(d)}this.updateBoundingBox(),ds._RestorePivotPoint(this.attachedMesh)}this._updateDummy()}),o.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(a)}),o.onDragEndObservable.add(h=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(h.pointerInfo,a)}),this._rotateAnchorsDragBehaviors.push(o),this._rotateAnchorsParent.addChild(a)}this._rootMesh.addChild(this._rotateAnchorsParent),this._scaleBoxesParent=new _t("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new Pe;for(let n=0;n<3;n++)for(let a=0;a<3;a++)for(let o=0;o<3;o++){const l=(n===1?1:0)+(a===1?1:0)+(o===1?1:0);if(l===1||l===3)continue;const c=l===2?ph("",{size:1},t.utilityLayerScene):this._getCornerMesh(t);l===0&&(c.rotationQuaternion=Pe.FromEulerAngles(a*.25*Math.PI,(o+3*n-n*o)*.25*Math.PI,0)),c.material=this._coloredMaterial,c._internalMetadata=l===2,c.isNearGrabbable=!0;const u=new D(n-1,a-1,o-1).normalize(),h=new sl({dragAxis:u});h.updateDragPlane=!1,h.moveAttached=!1;let d=0,f=0;c.addBehavior(h),h.onDragObservable.add(p=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const m=this.attachedMesh.parent;if(m&&m.scaling&&m.scaling.isNonUniformWithinEpsilon(.001)){fe.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}ds._RemoveAndStorePivotPoint(this.attachedMesh);let g=p.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(d+=g,this.scalingSnapDistance>0){const v=Math.floor(Math.abs(d)/this.scalingSnapDistance)*(d<0?-1:1),x=this.scalingSnapDistance*v;g=x-f,f=x}const _=new D(g,g,g),y=new D(f,f,f);l===2&&(_.x*=Math.abs(u.x),_.y*=Math.abs(u.y),_.z*=Math.abs(u.z)),_.scaleInPlace(this._scaleDragSpeed),_.multiplyInPlace(this._axisFactor),y.scaleInPlace(this._scaleDragSpeed),y.multiplyInPlace(this._axisFactor),y.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),D.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),D.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(c.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(y.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(c),d=0,f=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)}),h.onDragEndObservable.add(p=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(p.pointerInfo,c)}),this._scaleBoxesParent.addChild(c),this._scaleBoxesDragBehaviors.push(h)}this._rootMesh.addChild(this._scaleBoxesParent);const r=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add(n=>{r[n.event.pointerId]?n.pickInfo&&n.pickInfo.pickedMesh!=r[n.event.pointerId]&&(r[n.event.pointerId].material=this._coloredMaterial,delete r[n.event.pointerId],this._isHovered=!1):this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(a=>{n.pickInfo&&n.pickInfo.pickedMesh==a&&(r[n.event.pointerId]=a,a.material=this._hoverColoredMaterial,this._isHovered=!0)})}),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add(()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationAnchors(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))}),this.updateBoundingBox()}_getCornerMesh(e){if(!this._cornerMesh){const t=ph("",{width:.4,height:.4,depth:1.6},e.utilityLayerScene);t.position.z=.6;const i=ph("",{width:.4,height:1.6,depth:.4},e.utilityLayerScene);i.position.y=.6;const r=ph("",{width:1.6,height:.4,depth:.4},e.utilityLayerScene);return r.position.x=.6,this._cornerMesh=Ee.MergeMeshes([r,i,t],!0),this._cornerMesh}return this._cornerMesh.clone()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),ds._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),ds._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach(i=>{i.markAsDirty("scaling")}),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(()=>{this._updateDummy()})}}_selectNode(e){this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(t=>{t.isVisible=!e||t==e})}_unhoverMeshOnTouchUp(e,t){(e==null?void 0:e.event)instanceof PointerEvent&&(e==null?void 0:e.event.pointerType)==="touch"&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){ds._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=Pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=Pe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateAnchorsParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationAnchors(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),ds._RestorePivotPoint(this.attachedMesh))}_updateRotationAnchors(){const e=this._rotateAnchorsParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let r=0;r<2;r++){const n=t*4+i*2+r;if(t==0&&e[n].position.set(0,this._boundingDimensions.y*(i-.5),this._boundingDimensions.z*(r-.5)),t==1&&e[n].position.set(this._boundingDimensions.x*(i-.5),0,this._boundingDimensions.z*(r-.5)),t==2&&e[n].position.set(this._boundingDimensions.x*(i-.5),this._boundingDimensions.y*(r-.5),0),t==0&&(i||r)?Pe.FromEulerAnglesToRef(0,Math.PI*.5,0,e[n].rotationQuaternion):t==1&&Pe.FromEulerAnglesToRef(Math.PI*.5,0,0,e[n].rotationQuaternion),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[n].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[n].scaling.set(a,a,a)}else this.fixedDragMeshBoundsSize?e[n].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[n].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let r=0;r<3;r++)for(let n=0;n<3;n++){const a=(i===1?1:0)+(r===1?1:0)+(n===1?1:0);if(!(a===1||a===3)){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(r/2),this._boundingDimensions.z*(n/2)),e[t].position.addInPlace(new D(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const o=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(o,o,o)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateAnchorsParent.getChildMeshes().forEach((t,i)=>{i<4?t.setEnabled(e.indexOf("x")!=-1):i<8?t.setEnabled(e.indexOf("y")!=-1):t.setEnabled(e.indexOf("z")!=-1)})}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach(i=>{let r=e;t&&i._internalMetadata===!0&&(r=!1),i.setEnabled(r)})}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=ph("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new Pe,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach(e=>{e.releaseDrag()}),this._rotateAnchorsDragBehaviors.forEach(e=>{e.releaseDrag()}),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateAnchorsParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateAnchorsDragBehaviors.length=0,super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=o=>{o.isPickable=!1,o.getChildMeshes().forEach(l=>{t(l)})};t(e),e.rotationQuaternion||(e.rotationQuaternion=Pe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),r=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const n=ph("box",{size:1},e.getScene()),a=e.getHierarchyBoundingVectors();return a.max.subtractToRef(a.min,n.scaling),n.scaling.y===0&&(n.scaling.y=ci),n.scaling.x===0&&(n.scaling.x=ci),n.scaling.z===0&&(n.scaling.z=ci),n.position.set((a.max.x+a.min.x)/2,(a.max.y+a.min.y)/2,(a.max.z+a.min.z)/2),e.addChild(n),e.rotationQuaternion.copyFrom(r),e.position.copyFrom(i),e.removeChild(n),n.addChild(e),n.visibility=0,n}setCustomMesh(){fe.Error("Custom meshes are not supported on this gizmo")}}class d0 extends jn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Re.Gray(),i=is.DefaultUtilityLayer,r=32,n=null,a=!1,o=1,l=Re.Yellow(),c=Re.Gray()){var b;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new D,this._parent=n,this._coloredMaterial=new et("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Re(.1,.1,.1)),this._hoverMaterial=new et("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=l,this._hoverMaterial.specularColor=l,this._disableMaterial=new et("",i.utilityLayerScene),this._disableMaterial.diffuseColor=c,this._disableMaterial.alpha=.4,this._gizmoMesh=new Ee("",i.utilityLayerScene);const{rotationMesh:u,collider:h}=this._createGizmoMesh(this._gizmoMesh,o,r);this._rotationDisplayPlane=b_("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=Math.PI*.5,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),zi.ShadersStore.rotationGizmoVertexShader=d0._RotationGizmoVertexShader,zi.ShadersStore.rotationGizmoFragmentShader=d0._RotationGizmoFragmentShader,this._rotationShaderMaterial=new na("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=l,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,jn.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new sl({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=d0.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const d=new D,f=new he,p=new D;let m=new D;this.dragBehavior.onDragStartObservable.add(C=>{this.attachedNode&&(d.copyFrom(C.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(f),D.TransformCoordinatesToRef(C.dragPlanePoint,f,d),this._angles.x=Math.atan2(d.y,d.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,d.copyFrom(C.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});const g={snapDistance:0};let _=0;const y=new he,v=new Pe;this.dragBehavior.onDragObservable.add(C=>{if(this.attachedNode){const T=new D(1,1,1),w=new Pe(0,0,0,1),P=new D(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(T,w,P),!(Math.abs(Math.abs(T.x)-Math.abs(T.y))<=ci&&Math.abs(Math.abs(T.x)-Math.abs(T.z))<=ci)&&this.updateGizmoRotationToMatchAttachedMesh){fe.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}w.normalize();const R=this.updateGizmoPositionToMatchAttachedMesh?P:this._rootMesh.absolutePosition,I=C.dragPlanePoint.subtract(R).normalize(),L=d.subtract(R).normalize(),k=D.Cross(I,L),V=D.Dot(I,L);let H=Math.atan2(k.length(),V)*this.sensitivity;p.copyFrom(e),m.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(w.toRotationMatrix(f),m=D.TransformCoordinates(p,f));let j=!1;if(i.utilityLayerScene.activeCamera){const W=i.utilityLayerScene.activeCamera.position.subtract(R).normalize();D.Dot(W,m)>0&&(p.scaleInPlace(-1),m.scaleInPlace(-1),j=!0)}D.Dot(m,k)>0&&(H=-H),se.Vector3[0].set(H,0,0),this.dragBehavior.validateDrag(se.Vector3[0])||(H=0);let K=!1;if(this.snapDistance!=0)if(_+=H,Math.abs(_)>this.snapDistance){let W=Math.floor(Math.abs(_)/this.snapDistance);_<0&&(W*=-1),_=_%this.snapDistance,H=this.snapDistance*W,K=!0}else H=0;const U=Math.sin(H/2);if(v.set(p.x*U,p.y*U,p.z*U,Math.cos(H/2)),y.determinant()>0){const W=new D;v.toEulerAnglesToRef(W),Pe.RotationYawPitchRollToRef(W.y,-W.x,-W.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)w.multiplyToRef(v,w),w.normalize(),he.ComposeToRef(T,w,P,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(se.Matrix[0]);const W=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(se.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(W)}d.copyFrom(C.dragPlanePoint),K&&(g.snapDistance=H,this.onSnapObservable.notifyObservers(g)),this._angles.y+=H,this.angle+=j?-H:H,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const A={colliderMeshes:[h],gizmoMeshes:[u],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(b=this._parent)==null||b.addToAxisCache(this._gizmoMesh,A),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(C=>{var T;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=d0.MaxDragAngle,this._isHovered=A.colliderMeshes.indexOf((T=C==null?void 0:C.pickInfo)==null?void 0:T.pickedMesh)!=-1,!this._parent)){const w=A.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(A.gizmoMeshes,w)}}),this.dragBehavior.onEnabledObservable.add(C=>{this._setGizmoMeshMaterial(A.gizmoMeshes,C?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){const r=ug("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;const n=ug("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return n.material=this._coloredMaterial,n.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(n,jn.PreserveScaling),e.addChild(r,jn.PreserveScaling),{rotationMesh:n,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}d0.MaxDragAngle=Math.PI*9/20;d0._RotationGizmoVertexShader=` precision highp float; attribute vec3 position; attribute vec2 uv; uniform mat4 worldViewProjection; varying vec3 vPosition; varying vec2 vUV; void main(void) { gl_Position = worldViewProjection * vec4(position, 1.0); vUV = uv; }`;d0._RotationGizmoFragmentShader=` precision highp float; varying vec2 vUV; varying vec3 vPosition; uniform vec3 angles; uniform vec3 rotationColor; #define twopi 6.283185307 void main(void) { vec2 uv = vUV - vec2(0.5); float angle = atan(uv.y, uv.x) + 3.141592; float delta = gl_FrontFacing ? angles.y : -angles.y; float begin = angles.x - delta * angles.z; float start = (begin < (begin + delta)) ? begin : (begin + delta); float end = (begin > (begin + delta)) ? begin : (begin + delta); float len = sqrt(dot(uv,uv)); float opacity = 1. - step(0.5, len); float base = abs(floor(start / twopi)) * twopi; start += base; end += base; float intensity = 0.; for (int i = 0; i < 5; i++) { intensity += max(step(start, angle) - step(end, angle), 0.); angle += twopi; } gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity; } `;class E1e extends jn{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null})}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&fe.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t&&(t.sensitivity=e)})}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.additionalTransformNode=e})}constructor(e=is.DefaultUtilityLayer,t=32,i=!1,r=1,n,a){super(e),this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=a&&a.xOptions&&a.xOptions.color?a.xOptions.color:Re.Red().scale(.5),l=a&&a.yOptions&&a.yOptions.color?a.yOptions.color:Re.Green().scale(.5),c=a&&a.zOptions&&a.zOptions.color?a.zOptions.color:Re.Blue().scale(.5);this.xGizmo=new d0(new D(1,0,0),o,e,t,this,i,r),this.yGizmo=new d0(new D(0,1,0),l,e,t,this,i,r),this.zGizmo=new d0(new D(0,0,1),c,e,t,this,i,r),this.additionalTransformNode=a==null?void 0:a.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(u=>{a&&a.updateScale!=null&&(u.updateScale=a.updateScale),u.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),u.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),u.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,n?n.addToAxisCache(this._gizmoAxisCache):jn.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.anchorPoint=e})}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t.coordinatesMode=e})}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(t=>{t&&(t.customRotationQuaternion=e)})}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})}setCustomMesh(){fe.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class oP extends jn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new _t("plane",e),r=b_("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return r.material=t,r.parent=i,i}constructor(e,t=Re.Gray(),i=is.DefaultUtilityLayer,r=null,n=Re.Yellow(),a=Re.Gray()){var d;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ae,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new et("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Re(.1,.1,.1)),this._hoverMaterial=new et("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new et("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a,this._disableMaterial.alpha=.4,this._gizmoMesh=oP._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const l=new D,c={snapDistance:0};this.dragBehavior=new sl({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(f=>{if(this.attachedNode){if(this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(se.Vector3[0]),se.Vector3[0].addToRef(f.delta,se.Vector3[0]),this.dragBehavior.validateDrag(se.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(f.delta.x,f.delta.y,f.delta.z);else if(o+=f.dragDistance,Math.abs(o)>this.snapDistance){const p=Math.floor(Math.abs(o)/this.snapDistance);o=o%this.snapDistance,f.delta.normalizeToRef(l),l.scaleInPlace(this.snapDistance*p),this.attachedNode.getWorldMatrix().getTranslationToRef(se.Vector3[0]),se.Vector3[0].addToRef(l,se.Vector3[0]),this.dragBehavior.validateDrag(se.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(l.x,l.y,l.z),c.snapDistance=this.snapDistance*p,this.onSnapObservable.notifyObservers(c))}this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{this._dragging=!0}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1});const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const h={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(d=this._parent)==null||d.addToAxisCache(this._gizmoMesh,h),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(f=>{var p;if(!this._customMeshSet&&(this._isHovered=h.colliderMeshes.indexOf((p=f==null?void 0:f.pickInfo)==null?void 0:p.pickedMesh)!=-1,!this._parent)){const m=h.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(h.gizmoMeshes,m)}}),this.dragBehavior.onEnabledObservable.add(f=>{this._setGizmoMeshMaterial(h.gizmoMeshes,f?this._coloredMaterial:this._disableMaterial)})}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()})}}class fee extends jn{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null})}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.additionalTransformNode=e})}constructor(e=is.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this._planarGizmoEnabled=!1,this.xGizmo=new Bf(new D(1,0,0),Re.Red().scale(.5),e,this,t),this.yGizmo=new Bf(new D(0,1,0),Re.Green().scale(.5),e,this,t),this.zGizmo=new Bf(new D(0,0,1),Re.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new oP(new D(1,0,0),Re.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new oP(new D(0,1,0),Re.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new oP(new D(0,0,1),Re.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=r==null?void 0:r.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(n=>{n.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),n.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),n.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):jn.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))},this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.customRotationQuaternion=e)})}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)})}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)})}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.anchorPoint=e})}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t.coordinatesMode=e})}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.snapDistance=e)})}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(t=>{t&&(t.scaleRatio=e)})}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(e=>{e&&e.dispose()}),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){fe.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class T1e extends jn{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null})}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.additionalTransformNode=e})}constructor(e=is.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Ae,this.onDragObservable=new Ae,this.onDragEndObservable=new Ae,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new kf(new D(1,0,0),Re.Red().scale(.5),e,this,t),this.yGizmo=new kf(new D(0,1,0),Re.Green().scale(.5),e,this,t),this.zGizmo=new kf(new D(0,0,1),Re.Blue().scale(.5),e,this,t),this.additionalTransformNode=r==null?void 0:r.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(n=>{n.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),n.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),n.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):jn.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new et("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Re.Gray(),this._hoverMaterial=new et("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Re.Yellow(),this._disableMaterial=new et("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Re.Gray(),this._disableMaterial.alpha=.4;const e=new kf(new D(0,1,0),Re.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=n6("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=n6("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)})):fe.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.anchorPoint=e)})}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.customRotationQuaternion=e)})}set coordinatesMode(e){e==0&&fe.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t.coordinatesMode=1})}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.snapDistance=e)})}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.incrementalSnap=e)})}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.scaleRatio=e)})}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(t=>{t&&(t.sensitivity=e)})}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(e=>{e&&e.dispose()}),this._observables.forEach(e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach(e=>{e&&e.dispose()}),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()})}}class W4t{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach(t=>{t&&t.isDragging&&(e=!0)}),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach(t=>{t&&(t.scaleRatio=e)})}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach(t=>{t&&(t.coordinatesMode=e)})}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=is.DefaultUtilityLayer,r=is.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new Ae,this.onAttachedToNodeObservable=new Ae,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Re.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=1,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new V9e,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=r,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const n=this._attachToMeshPointerObserver(e),a=jn.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[n,a]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add(i=>{if(this.usePointerToAttachGizmos&&i.type==yt.POINTERDOWN)if(i.pickInfo&&i.pickInfo.pickedMesh){if(this.enableAutoPicking){let r=i.pickInfo.pickedMesh;if(this.attachableMeshes==null)for(;r&&r.parent!=null;)r=r.parent;else{let n=!1;this.attachableMeshes.forEach(a=>{r&&(r==a||r.isDescendantOf(a))&&(r=a,n=!0)}),n||(r=null)}r instanceof Li?this._attachedMesh!=r&&this.attachToMesh(r):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)})}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new fee(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new E1e(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new T1e(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new S1e(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach((t,i)=>{this._gizmoAxisCache.set(i,t)})}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach(e=>{e==null||e.releaseDrag()})}dispose(){var e,t;this._pointerObservers.forEach(i=>{this._scene.onPointerObservable.remove(i)});for(const i in this.gizmos){const r=this.gizmos[i];r&&r.dispose()}this._defaultKeepDepthUtilityLayer!==is._DefaultKeepDepthUtilityLayer&&((e=this._defaultKeepDepthUtilityLayer)==null||e.dispose()),this._defaultUtilityLayer!==is._DefaultUtilityLayer&&((t=this._defaultUtilityLayer)==null||t.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class Gx extends Zi{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=he.Identity(),this._projectionMatrix=he.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=D.Zero()),D.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=D.Zero()),D.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=D.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=D.Cross(this.direction,Da.Y),t=D.Cross(e,this.direction);return D.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=D.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=he.Identity()),he.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=se.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),D.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(D.Dot(t,D.Up()))===1&&(t.z=1e-13);const r=se.Vector3[1];return i.addToRef(t,r),he.LookAtLHToRef(i,r,D.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}F([Pn()],Gx.prototype,"position",null);F([Pn()],Gx.prototype,"direction",null);F([X()],Gx.prototype,"shadowMinZ",null);F([X()],Gx.prototype,"shadowMaxZ",null);ns.AddNodeConstructor("Light_Type_1",(s,e)=>()=>new dc(s,D.Zero(),e));class dc extends Gx{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Zi.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&he.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t.minZ,this.shadowMaxZ!==void 0?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const u=D.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let h=Number.MAX_VALUE,d=-Number.MAX_VALUE;for(let f=0;fthis._orthoRight&&(this._orthoRight=u.x),u.y>this._orthoTop&&(this._orthoTop=u.y),this.autoCalcShadowZBounds&&(u.zd&&(d=u.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=h,this._shadowMaxZ=d)}const n=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,c=this.getScene().getEngine().useReverseDepthBuffer;he.OrthoOffCenterLHToRef(this._orthoLeft-n*this.shadowOrthoScale,this._orthoRight+n*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,c?l:o,c?o:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}F([X()],dc.prototype,"shadowFrustumSize",null);F([X()],dc.prototype,"shadowOrthoScale",null);F([X()],dc.prototype,"autoUpdateExtends",void 0);F([X()],dc.prototype,"autoCalcShadowZBounds",void 0);F([X("orthoLeft")],dc.prototype,"_orthoLeft",void 0);F([X("orthoRight")],dc.prototype,"_orthoRight",void 0);F([X("orthoTop")],dc.prototype,"_orthoTop",void 0);F([X("orthoBottom")],dc.prototype,"_orthoBottom",void 0);ve("BABYLON.DirectionalLight",dc);function Gk(s,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=kc("",{slice:.5,diameter:e.diameter,segments:e.segments},t),r=iD("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);r.rotation.x=-Math.PI/2,r.parent=i;const n=Ee.MergeMeshes([r,i],!0);return n.name=s,n}const K4t={CreateHemisphere:Gk};Ee.CreateHemisphere=(s,e,t,i)=>Gk(s,{segments:e,diameter:t},i);ns.AddNodeConstructor("Light_Type_2",(s,e)=>()=>new $l(s,D.Zero(),D.Zero(),0,0,e));class $l extends Gx{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&($l._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):$l._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return e.onGeneratedObservable!==void 0}static _IsTexture(e){return e.onLoadObservable!==void 0}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,n,a){super(e,a),this._innerAngle=0,this._projectionTextureMatrix=he.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=D.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=D.Zero(),this._projectionTextureViewLightMatrix=he.Zero(),this._projectionTextureProjectionLightMatrix=he.Zero(),this._projectionTextureScalingMatrix=he.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=n}getClassName(){return"SpotLight"}getTypeID(){return Zi.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;const n=this._shadowAngleScale*this._angle,a=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;he.PerspectiveFovLHToRef(n,1,l?o:a,l?a:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),he.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,n=1/Math.tan(this._angle/2);he.FromValuesToRef(n/1,0,0,0,0,n,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof xe){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;he.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=D.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=D.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return this.computeTransformedInformation()?i=D.Normalize(this.transformedDirection):i=D.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}}F([X()],$l.prototype,"angle",null);F([X()],$l.prototype,"innerAngle",null);F([X()],$l.prototype,"shadowAngleScale",null);F([X()],$l.prototype,"exponent",void 0);F([X()],$l.prototype,"projectionTextureLightNear",null);F([X()],$l.prototype,"projectionTextureLightFar",null);F([X()],$l.prototype,"projectionTextureUpDirection",null);F([ii("projectedLightTexture")],$l.prototype,"_projectionTexture",void 0);ve("BABYLON.SpotLight",$l);class $p extends jn{constructor(e=is.DefaultUtilityLayer){super(e),this._cachedPosition=new D,this._cachedForward=new D(0,0,1),this._pointerObserver=null,this.onClickedObservable=new Ae,this._light=null,this.attachedMesh=new Ee("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new _t("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new et("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Re(.5,.5,.5),this._material.specularColor=new Re(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(t=>{this._light&&(this._isHovered=!!(t.pickInfo&&this._rootMesh.getChildMeshes().indexOf(t.pickInfo.pickedMesh)!=-1),this._isHovered&&t.event.button===0&&this.onClickedObservable.notifyObservers(this._light))},yt.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){fe.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof $f?this._lightMesh=$p._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof dc?this._lightMesh=$p._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof $l?this._lightMesh=$p._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=$p._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(i=>{i.material=this._material}),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new Pe,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const i=this._getMeshForward();this._cachedForward.copyFrom(i)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(se.Vector3[0]),e=se.Vector3[0]),e}_update(){if(super._update(),!!this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new D(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(D.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new D(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else D.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Ee("hemisphereLight",e),i=Gk(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;const r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace($p._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Ee("pointLight",e),i=kc(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;const r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace($p._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Ee("spotLight",e),i=kc(t.name,{segments:10,diameter:1},e);i.parent=t;const r=Gk(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;const n=this._CreateLightLines(2,e);return n.parent=t,t.scaling.scaleInPlace($p._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Ee("directionalLight",e),i=new Ee(t.name,e);i.parent=t;const r=kc(t.name,{diameter:1.2,segments:10},e);r.parent=i;const n=ou(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);n.parent=i;let a=n.clone(t.name);a.scaling.y=.5,a.position.x+=1.25;let o=n.clone(t.name);o.scaling.y=.5,o.position.x+=-1.25;const l=ou(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return l.position.y+=3,l.parent=i,a=l.clone(t.name),a.position.y=1.5,a.position.x+=1.25,o=l.clone(t.name),o.position.y=1.5,o.position.x+=-1.25,i.scaling.scaleInPlace($p._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}$p._Scale=.007;$p._CreateLightLines=(s,e)=>{const i=new Ee("root",e);i.rotation.x=Math.PI/2;const r=new Ee("linePivot",e);r.parent=i;const n=ou("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},e);if(n.position.y=n.scaling.y/2+1.2,n.parent=r,s<2)return r;for(let o=0;o<4;o++){const l=r.clone("lineParentClone");l.rotation.z=Math.PI/4,l.rotation.y=Math.PI/2+Math.PI/2*o,l.getChildMeshes()[0].scaling.y=.5,l.getChildMeshes()[0].scaling.x=l.getChildMeshes()[0].scaling.z=.8,l.getChildMeshes()[0].position.y=l.getChildMeshes()[0].scaling.y/2+1.2}if(s<3)return i;for(let o=0;o<4;o++){const l=r.clone("linePivotClone");l.rotation.z=Math.PI/2,l.rotation.y=Math.PI/2*o}if(s<4)return i;for(let o=0;o<4;o++){const l=r.clone("linePivotClone");l.rotation.z=Math.PI+Math.PI/4,l.rotation.y=Math.PI/2+Math.PI/2*o,l.getChildMeshes()[0].scaling.y=.5,l.getChildMeshes()[0].scaling.x=l.getChildMeshes()[0].scaling.z=.8,l.getChildMeshes()[0].position.y=l.getChildMeshes()[0].scaling.y/2+1.2}if(s<5)return i;const a=r.clone("linePivotClone");return a.rotation.z=Math.PI,i};class lP extends jn{constructor(e=is.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new Ae,this._camera=null,this._invProjection=new he,this._material=new et("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Re(.5,.5,.5),this._material.specularColor=new Re(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(r=>{this._camera&&(this._isHovered=!!(r.pickInfo&&this._rootMesh.getChildMeshes().indexOf(r.pickInfo.pickedMesh)!=-1),this._isHovered&&r.event.button===0&&this.onClickedObservable.notifyObservers(this._camera))},yt.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){var t;if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=lP._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(n=>{n.material=this._material}),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const i=((t=this._frustumLinesColor)==null?void 0:t.toColor4(1))??new Ze(1,1,1,1);this._cameraLinesMesh=lP._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,i),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ{this._outputTexture?f.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):f.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>NRt),void 0),Ue(()=>Promise.resolve().then(()=>kRt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>ERt),void 0),Ue(()=>Promise.resolve().then(()=>RRt),void 0)])),super._gatherImports(e,t)}updateEffect(e=null,t=null,i=null,r,n,a){this._updateParameters(n,a)}_updateParameters(e,t){const i=this._kernel,r=(i-1)/2;let n=[],a=[],o=0;for(let g=0;g0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,r=-(e*e/(2*t*t));return 1/i*Math.exp(r)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return qe.Parse(()=>new Ho(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}}F([X("kernel")],Ho.prototype,"_kernel",void 0);F([X("packedFloat")],Ho.prototype,"_packedFloat",void 0);F([nz()],Ho.prototype,"direction",void 0);ve("BABYLON.BlurPostProcess",Ho);class Av extends Rs{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,n=0,a=xe.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,r,!0,n,!1,a,o),this.mirrorPlane=new Xl(0,1,0,1),this._transformMatrix=he.Zero(),this._mirrorMatrix=he.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,i=this.getScene(),!i)return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});const l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var u;(u=l._debugPushGroup)==null||u.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var u;(u=l._debugPopGroup)==null||u.call(l,1)});let c;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),he.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),c=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=D.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=c})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new Ho("horizontal blur",new we(1,0),this._blurKernelX,this._blurRatio,null,xe.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,this._blurRatio===1&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new Ho("vertical blur",new we(0,1),this._blurKernelY,this._blurRatio,null,xe.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=this._blurRatio!==1,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Av(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var t;super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(t=this._sceneUBO)==null||t.dispose()}}xe._CreateMirror=(s,e,t,i)=>new Av(s,e,t,i);const eMe=.8;class _a extends $r{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(he.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(n=>r+=n),new _a(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){const n=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const a=new _a(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=n,a}constructor(e,t,i=null,r=!1,n=null,a=null,o=null,l=5,c=!1,u=null,h=!1,d=eMe,f=0,p,m){var y;super(t),this.onLoadObservable=new Ae,this.boundingBoxPosition=D.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new he,this._buffer=null,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=he.Identity(),this.coordinatesMode=xe.CUBIC_MODE;let g=null,_=null;i!==null&&!Array.isArray(i)?(g=i.extensions??null,this._noMipmap=i.noMipmap??!1,n=i.files??null,_=i.buffer??null,this._format=i.format??5,c=i.prefiltered??!1,u=i.forcedExtension??null,this._createPolynomials=i.createPolynomials??!1,this._lodScale=i.lodScale??eMe,this._lodOffset=i.lodOffset??0,this._loaderOptions=i.loaderOptions,this._useSRGBBuffer=i.useSRGBBuffer,a=i.onLoad??null,o=i.onError??null):(this._noMipmap=r,this._format=l,this._createPolynomials=h,g=i,this._loaderOptions=p,this._useSRGBBuffer=m,this._lodScale=d,this._lodOffset=f),!(!e&&!n)&&this.updateURL(e,u,a,c,o,g,(y=this.getScene())==null?void 0:y.useDelayedTextureLoading,n,_)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,r=!1,n=null,a=null,o=!1,l=null,c=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);const u=e.lastIndexOf("."),h=t||(u>-1?e.substring(u).toLowerCase():""),d=h.indexOf(".dds")===0,f=h.indexOf(".env")===0,p=h.indexOf(".basis")===0;if(f?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),l)this._files=l;else if(!p&&!f&&!d&&!a&&(a=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,a){for(let m=0;mo.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!((a=this.getScene())!=null&&a.useRightHandedSystem)))return;const t=se.Vector3[0],i=se.Quaternion[0],r=se.Vector3[1];this._textureMatrix.decompose(t,i,r),i.z*=-1,i.w*=-1,he.ComposeToRef(t,i,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(e=this.getScene())!=null&&e.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var o;const i=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const n=()=>{var l;this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),(l=this.getScene())==null||l.markAllMaterialsAsDirty(1)),e&&e()},a=(l,c)=>{this._loadingError=!0,this._errorObject={message:l,exception:c},t&&t(l,c),xe.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Me.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer,this._buffer),(o=this._texture)==null||o.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const r=qe.Parse(()=>{let n=!1;return e.prefiltered&&(n=e.prefiltered),new _a(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=D.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=D.FromArray(e.boundingBoxSize)),e.animations)for(let n=0;n{const i=new _a(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}F([X()],_a.prototype,"url",void 0);F([Pn()],_a.prototype,"boundingBoxPosition",void 0);F([Pn()],_a.prototype,"boundingBoxSize",null);F([X("rotationY")],_a.prototype,"rotationY",null);F([X("files")],_a.prototype,"_files",void 0);F([X("forcedExtension")],_a.prototype,"_forcedExtension",void 0);F([X("extensions")],_a.prototype,"_extensions",void 0);F([xJ("textureMatrix")],_a.prototype,"_textureMatrix",void 0);F([xJ("textureMatrixRefraction")],_a.prototype,"_textureMatrixRefraction",void 0);xe._CubeTextureParser=_a.Parse;ve("BABYLON.CubeTexture",_a);class H4t extends _s{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class xr extends aa{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t=t*2,this.reflectionReflectance0=xr.StandardReflectance0*t,this.reflectionReflectance90=xr.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=xr.StandardReflectance0+(1-xr.StandardReflectance0)*t,this.reflectionReflectance90=xr.StandardReflectance90+(1-xr.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t,i=!1){super(e,t),this.primaryColor=Re.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=D.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new no(16),this._reflectionControls=mt.Zero(),this._white=Re.White(),this._primaryShadowColor=Re.Black(),this._primaryHighlightColor=Re.Black(),this._shadersLoaded=!1;const r=this.getScene().getEngine();r.isWebGPU&&!i&&(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new zt(r,void 0,void 0,this.name,!0),this._shaderLanguage=1),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!(this._diffuseTexture&&this._diffuseTexture.isRenderTarget||this._reflectionTexture&&this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new H4t);const n=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(du(n,e,a,!1,this._maxSimultaneousLights),a._needNormals=!0,qw(n,a),a._areTexturesDirty){if(a._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Je.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;rn(this._diffuseTexture,a,"DIFFUSE"),a.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,a.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,a.OPACITYFRESNEL=this._opacityFresnel}else a.DIFFUSE=!1,a.DIFFUSEDIRECTUV=0,a.DIFFUSEHASALPHA=!1,a.GAMMADIFFUSE=!1,a.OPACITYFRESNEL=!1;const l=this._reflectionTexture;if(l&&Je.ReflectionTextureEnabled){if(!l.isReadyOrNotBlocking())return!1;switch(a.REFLECTION=!0,a.GAMMAREFLECTION=l.gammaSpace,a.RGBDREFLECTION=l.isRGBD,a.REFLECTIONBLUR=this._reflectionBlur>0,a.LODINREFLECTIONALPHA=l.lodLevelInAlpha,a.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,a.REFLECTIONBGR=this.switchToBGR,l.coordinatesMode===xe.INVCUBIC_MODE&&(a.INVERTCUBICMAP=!0),a.REFLECTIONMAP_3D=l.isCube,a.REFLECTIONMAP_OPPOSITEZ=a.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!l.invertZ:l.invertZ,l.coordinatesMode){case xe.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case xe.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case xe.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case xe.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case xe.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case xe.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case xe.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case xe.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case xe.CUBIC_MODE:case xe.INVCUBIC_MODE:default:a.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(a.REFLECTIONFRESNEL=!0,a.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1)}else a.REFLECTION=!1,a.REFLECTIONFRESNEL=!1,a.REFLECTIONFALLOFF=!1,a.REFLECTIONBLUR=!1,a.REFLECTIONMAP_3D=!1,a.REFLECTIONMAP_SPHERICAL=!1,a.REFLECTIONMAP_PLANAR=!1,a.REFLECTIONMAP_CUBIC=!1,a.REFLECTIONMAP_PROJECTION=!1,a.REFLECTIONMAP_SKYBOX=!1,a.REFLECTIONMAP_EXPLICIT=!1,a.REFLECTIONMAP_EQUIRECTANGULAR=!1,a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,a.INVERTCUBICMAP=!1,a.REFLECTIONMAP_OPPOSITEZ=!1,a.LODINREFLECTIONALPHA=!1,a.GAMMAREFLECTION=!1,a.RGBDREFLECTION=!1}a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.USERGBCOLOR=this._useRGBColor,a.NOISE=this._enableNoise}if(a._areLightsDirty&&(a.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),a.BACKMAT_SHADOWONLY=this._shadowOnly),a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a)}if(a._areMiscDirty&&(a.REFLECTIONMAP_3D&&this._enableGroundProjection?(a.PROJECTED_GROUND=!0,a.REFLECTIONMAP_SKYBOX=!0):a.PROJECTED_GROUND=!1),Kc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),a),Hc(n,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),Na(e,a,!1,!0,!1)&&e&&!n.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent($.NormalKind)&&(e.createNormals(!0),fe.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),a.isDirty){a.markAsProcessed(),n.resetCachedMaterial();const l=new oa;a.FOG&&l.addFallback(0,"FOG"),a.POINTSIZE&&l.addFallback(1,"POINTSIZE"),a.MULTIVIEW&&l.addFallback(0,"MULTIVIEW"),Zo(a,l,this._maxSimultaneousLights);const c=[$.PositionKind];a.NORMAL&&c.push($.NormalKind),a.UV1&&c.push($.UVKind),a.UV2&&c.push($.UV2Kind),Vu(c,e,a,l),Ya(c,a);const u=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];fo(u);const h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];lr&&(lr.PrepareUniforms(u,a),lr.PrepareSamplers(h,a)),po({uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});const f=a.toString(),p=n.getEngine().createEffect("background",{attributes:c,uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:f,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>mAt),void 0),Ue(()=>Promise.resolve().then(()=>RAt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>KAt),void 0),Ue(()=>Promise.resolve().then(()=>abt),void 0)]),this._shadersLoaded=!0}},o);t.setEffect(p,a,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(a._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){this._primaryColorShadowLevel===0&&this._primaryColorHighlightLevel===0||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e),ql(t,this._activeEffect);const o=this._mustRebind(r,a,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a);const l=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync||i._drawWrapper._forceRebindOnNextCall)&&(r.texturesEnabled&&(this._diffuseTexture&&Je.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),sn(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&Je.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),n.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&Je.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&Je.ReflectionTextureEnabled&&(n.REFLECTIONBLUR&&n.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):n.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),n.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),n.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),Xa(this._activeEffect,this,r),r.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(a,"Material"),this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(r.lightsEnabled&&hu(r,t,this._activeEffect,n,this._maxSimultaneousLights),this.bindView(a),ml(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&uo(n,a,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!(super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return qe.Clone(()=>new xr(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return qe.Parse(()=>new xr(e.name,t),e,t,i)}}xr.StandardReflectance0=.05;xr.StandardReflectance90=.5;F([br()],xr.prototype,"_primaryColor",void 0);F([Fe("_markAllSubMeshesAsLightsDirty")],xr.prototype,"primaryColor",void 0);F([br()],xr.prototype,"__perceptualColor",void 0);F([X()],xr.prototype,"_primaryColorShadowLevel",void 0);F([X()],xr.prototype,"_primaryColorHighlightLevel",void 0);F([Fe("_markAllSubMeshesAsLightsDirty")],xr.prototype,"primaryColorHighlightLevel",null);F([ii()],xr.prototype,"_reflectionTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionTexture",void 0);F([X()],xr.prototype,"_reflectionBlur",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionBlur",void 0);F([ii()],xr.prototype,"_diffuseTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"diffuseTexture",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"shadowLights",void 0);F([X()],xr.prototype,"_shadowLevel",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"shadowLevel",void 0);F([Pn()],xr.prototype,"_sceneCenter",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"sceneCenter",void 0);F([X()],xr.prototype,"_opacityFresnel",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"opacityFresnel",void 0);F([X()],xr.prototype,"_reflectionFresnel",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionFresnel",void 0);F([X()],xr.prototype,"_reflectionFalloffDistance",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionFalloffDistance",void 0);F([X()],xr.prototype,"_reflectionAmount",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionAmount",void 0);F([X()],xr.prototype,"_reflectionReflectance0",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionReflectance0",void 0);F([X()],xr.prototype,"_reflectionReflectance90",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"reflectionReflectance90",void 0);F([X()],xr.prototype,"_useRGBColor",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"useRGBColor",void 0);F([X()],xr.prototype,"_enableNoise",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"enableNoise",void 0);F([X()],xr.prototype,"_maxSimultaneousLights",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"maxSimultaneousLights",void 0);F([X()],xr.prototype,"_shadowOnly",void 0);F([Fe("_markAllSubMeshesAsLightsDirty")],xr.prototype,"shadowOnly",void 0);F([Jme()],xr.prototype,"_imageProcessingConfiguration",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],xr.prototype,"enableGroundProjection",void 0);F([X()],xr.prototype,"projectedGroundRadius",void 0);F([X()],xr.prototype,"projectedGroundHeight",void 0);ve("BABYLON.BackgroundMaterial",xr);class Sx{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Re(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Re(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:D.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(i,r)=>{this.onErrorObservable.notifyObservers({message:i,exception:r})},this._options={...Sx._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new Ae,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new Ze(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof $r){this._scene.environmentTexture=this._options.environmentTexture;return}const e=_a.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Ee("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||this._scene.meshes.length===1)return{groundSize:e,skyboxSize:t,rootPosition:i};const r=this._scene.getWorldExtends(a=>a!==this._ground&&a!==this._rootMesh&&a!==this._skybox),n=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Kr&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,t=e);const a=n.length();a>e&&(e=a*2,t=e),e*=1.1,t*=1.5,i=r.min.add(n.scale(.5)),i.y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=b_("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.isPickable=!1,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new xr("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof $r){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new xe(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){const t=xe.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Av("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,xe.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Xl(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let r=0;r{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new xr("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof $r){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new _a(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=xe.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}Sx._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";Sx._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";Sx._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class _h extends _t{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=xe.CLAMP_ADDRESSMODE,this._texture.wrapV=xe.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=xe.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=xe.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,n=null){super(e,r),this.onError=n,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=_h.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new Ae,this.onLoadObservable=new Ae,r=this.getScene(),e=e||"textureDome",i.resolution=Math.abs(i.resolution)|0||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=i.autoPlay===void 0?!0:!!i.autoPlay,i.loop=i.loop===void 0?!0:!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?r.activeCamera.maxZ*.48:1e3),i.useDirectMapping===void 0?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,i.faceForward===void 0&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=kc(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Ee.BACKSIDE},r);const a=this._material=new xr(e+"_material",r);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const o=this._initTexture(t,r,i);if(this.texture=o,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=kc("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:Ee.BACKSIDE},r),this._halfDomeMask.rotate(Da.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){const l=r.activeCamera,c=D.Forward(),u=D.TransformNormal(c,l.getViewMatrix());u.normalize(),this.rotation.y=Math.acos(D.Dot(c,u))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case _h.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case _h.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const t=this._halfDome?0:.5,i=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(r=>{let n=r.isRightCamera;this._crossEye&&(n=!n),n?this._texture.uOffset=t:this._texture.uOffset=i});break}case _h.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(t=>{let i=t.isRightCamera;this._crossEye&&(i=!i),this._texture.vOffset=i?.5:0});break}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}_h.MODE_MONOSCOPIC=0;_h.MODE_TOPBOTTOM=1;_h.MODE_SIDEBYSIDE=2;class sw extends _h{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new xe(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(r,n)=>{this.onLoadErrorObservable.notifyObservers(r||"Unknown error occured"),this.onError&&this.onError(r,n)})}}sw.MODE_MONOSCOPIC=_h.MODE_MONOSCOPIC;sw.MODE_TOPBOTTOM=_h.MODE_TOPBOTTOM;sw.MODE_SIDEBYSIDE=_h.MODE_SIDEBYSIDE;const j4t="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==";let X4t=0;const Hz=s=>{if(!s.environmentBRDFTexture){const e=s.useDelayedTextureLoading;s.useDelayedTextureLoading=!1;const t=s._blockEntityCollection;s._blockEntityCollection=!1;const i=xe.CreateFromBase64String(j4t,"EnvironmentBRDFTexture"+X4t++,s,!0,!1,xe.BILINEAR_SAMPLINGMODE);s._blockEntityCollection=t;const r=s.getEngine().getLoadedTexturesCache(),n=r.indexOf(i.getInternalTexture());n!==-1&&r.splice(n,1),i.isRGBD=!0,i.wrapU=xe.CLAMP_ADDRESSMODE,i.wrapV=xe.CLAMP_ADDRESSMODE,s.environmentBRDFTexture=i,s.useDelayedTextureLoading=e,zk.ExpandRGBDTexture(i);const a=s.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const o=s.onBeforeRenderObservable.add(()=>{i.isReady()&&(s.onBeforeRenderObservable.remove(o),zk.ExpandRGBDTexture(i))})});s.onDisposeObservable.add(()=>{s.getEngine().onContextRestoredObservable.remove(a)})}return s.environmentBRDFTexture},Y4t={GetEnvironmentBRDFTexture:Hz};class Q4t extends _s{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Ic extends fu{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new Q4t,t),this._useEnergyConservation=Ic.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Ic.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Ic.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Ic.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Ic.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Ic.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Ic.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Ic.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Ic.DEFAULT_USE_ENERGY_CONSERVATION=!0;Ic.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Ic.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Ic.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Ic.prototype,"useEnergyConservation",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Ic.prototype,"useSmithVisibilityHeightCorrelated",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Ic.prototype,"useSphericalHarmonics",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Ic.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);class Qke extends _s{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}}class Xo extends fu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new Qke,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Xo._DefaultIndexOfRefraction,this.indexOfRefraction=Xo._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=Re.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const r=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&Je.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&Je.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&Je.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking()))}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.ClearCoatTextureEnabled?rn(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Je.ClearCoatTextureEnabled?rn(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Je.ClearCoatBumpTextureEnabled?rn(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Xo._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Je.ClearCoatTintTextureEnabled?(rn(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var u,h,d,f;if(!this._isEnabled)return;const n=r.materialDefines,a=this._material.isFrozen,o=this._material._disableBumpMap,l=this._material._invertNormalMapX,c=this._material._invertNormalMapY;if(!e.useUbo||!a||!e.isSync){(this._texture||this._textureRoughness)&&Je.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",((u=this._texture)==null?void 0:u.coordinatesIndex)??0,((h=this._texture)==null?void 0:h.level)??0,((d=this._textureRoughness)==null?void 0:d.coordinatesIndex)??0,((f=this._textureRoughness)==null?void 0:f.level)??0),this._texture&&sn(this._texture,e,"clearCoat"),this._textureRoughness&&!n.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&sn(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&Je.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),sn(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",l?1:-1,c?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",l?-1:1,c?-1:1)),this._tintTexture&&Je.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),sn(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const p=1-this._indexOfRefraction,m=1+this._indexOfRefraction,g=Math.pow(-p/m,2),_=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",g,_,p,m),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&Je.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!n.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Je.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&Je.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Je.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,n;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(r=this._bumpTexture)==null||r.dispose(),(n=this._tintTexture)==null||n.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Xo._DefaultIndexOfRefraction=1.5;F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"isEnabled",void 0);F([X()],Xo.prototype,"intensity",void 0);F([X()],Xo.prototype,"roughness",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"indexOfRefraction",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"texture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"useRoughnessFromMainTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"textureRoughness",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"remapF0OnInterfaceChange",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"bumpTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"isTintEnabled",void 0);F([br()],Xo.prototype,"tintColor",void 0);F([X()],Xo.prototype,"tintColorAtDistance",void 0);F([X()],Xo.prototype,"tintThickness",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Xo.prototype,"tintTexture",void 0);class $ke extends _s{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class Uc extends fu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new $ke,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Uc._DefaultMinimumThickness,this.maximumThickness=Uc._DefaultMaximumThickness,this.indexOfRefraction=Uc._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&Je.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.IridescenceTextureEnabled?rn(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&Je.IridescenceTextureEnabled?rn(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){var r,n,a,o;if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&((this._texture||this._thicknessTexture)&&Je.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",((r=this._texture)==null?void 0:r.coordinatesIndex)??0,((n=this._texture)==null?void 0:n.level)??0,((a=this._thicknessTexture)==null?void 0:a.coordinatesIndex)??0,((o=this._thicknessTexture)==null?void 0:o.level)??0),this._texture&&sn(this._texture,e,"iridescence"),this._thicknessTexture&&sn(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Je.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&Je.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._thicknessTexture)==null||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}Uc._DefaultMinimumThickness=100;Uc._DefaultMaximumThickness=400;Uc._DefaultIndexOfRefraction=1.3;F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Uc.prototype,"isEnabled",void 0);F([X()],Uc.prototype,"intensity",void 0);F([X()],Uc.prototype,"minimumThickness",void 0);F([X()],Uc.prototype,"maximumThickness",void 0);F([X()],Uc.prototype,"indexOfRefraction",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Uc.prototype,"texture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Uc.prototype,"thicknessTexture",void 0);class Zke extends _s{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Wx extends fu{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new Zke,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new we(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Je.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent($.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.AnisotropicTextureEnabled?rn(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&(this._texture&&Je.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),sn(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Je.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),e.legacy===void 0&&(this.legacy=!0)}}F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Wx.prototype,"isEnabled",void 0);F([X()],Wx.prototype,"intensity",void 0);F([nz()],Wx.prototype,"direction",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Wx.prototype,"texture",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Wx.prototype,"legacy",void 0);class qke extends _s{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class L0 extends fu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new qke,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Re.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&Je.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=this._roughness!==null,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Je.SheenTextureEnabled?(rn(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Je.SheenTextureEnabled?rn(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var o,l,c,u;if(!this._isEnabled)return;const n=r.materialDefines,a=this._material.isFrozen;(!e.useUbo||!a||!e.isSync)&&((this._texture||this._textureRoughness)&&Je.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",((o=this._texture)==null?void 0:o.coordinatesIndex)??0,((l=this._texture)==null?void 0:l.level)??0,((c=this._textureRoughness)==null?void 0:c.coordinatesIndex)??0,((u=this._textureRoughness)==null?void 0:u.level)??0),this._texture&&sn(this._texture,e,"sheen"),this._textureRoughness&&!n.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&sn(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&Je.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!n.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Je.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"isEnabled",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"linkSheenWithAlbedo",void 0);F([X()],L0.prototype,"intensity",void 0);F([br()],L0.prototype,"color",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"texture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"useRoughnessFromMainTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"roughness",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"textureRoughness",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],L0.prototype,"albedoScaling",void 0);class Jke extends _s{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Fn extends fu{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Jke,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Re.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Re.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Je.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking()||this._translucencyColorTexture&&Je.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking()||this._translucencyIntensityTexture&&Je.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&Je.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0;return}if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&Je.ThicknessTextureEnabled&&rn(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Je.RefractionIntensityTextureEnabled&&rn(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Je.TranslucencyIntensityTextureEnabled&&rn(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&Je.TranslucencyColorTextureEnabled&&rn(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&Je.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled))if(this.maximumThickness===0&&this.minimumThickness===0)e.updateFloat2("vThicknessParam",0,0);else{r.getRenderingMesh().getWorldMatrix().decompose(se.Vector3[0]);const n=Math.max(Math.abs(se.Vector3[0].x),Math.abs(se.Vector3[0].y),Math.abs(se.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*n,(this.maximumThickness-this.minimumThickness)*n)}}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const n=r.materialDefines,a=this._material.isFrozen,o=this._material.realTimeFiltering,l=n.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&Je.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),sn(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Je.RefractionIntensityTextureEnabled&&n.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),sn(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&Je.TranslucencyColorTextureEnabled&&n.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),sn(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&Je.TranslucencyIntensityTextureEnabled&&n.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),sn(this._translucencyIntensityTexture,e,"translucencyIntensity")),c&&Je.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",c.getRefractionTextureMatrix());let u=1;c.isCube||c.depth&&(u=c.depth);const h=c.getSize().width,d=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",c.level,1/d,u,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",h,c.lodGenerationScale,c.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",h,At.Log2(h)),c.boundingBoxSize){const f=c;e.updateVector3("vRefractionPosition",f.boundingBoxPosition),e.updateVector3("vRefractionSize",f.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&Je.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Je.RefractionIntensityTextureEnabled&&n.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Je.TranslucencyIntensityTextureEnabled&&n.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&Je.TranslucencyColorTextureEnabled&&n.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),c&&Je.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",c):(e.setTexture("refractionSampler",c._lodTextureMid||c),e.setTexture("refractionSamplerLow",c._lodTextureLow||c),e.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Je.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!(Je.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"isRefractionEnabled",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"isTranslucencyEnabled",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"isDispersionEnabled",void 0);F([X(),Fe("_markScenePrePassDirty")],Fn.prototype,"isScatteringEnabled",void 0);F([X()],Fn.prototype,"_scatteringDiffusionProfileIndex",void 0);F([X()],Fn.prototype,"refractionIntensity",void 0);F([X()],Fn.prototype,"translucencyIntensity",void 0);F([X()],Fn.prototype,"useAlbedoToTintRefraction",void 0);F([X()],Fn.prototype,"useAlbedoToTintTranslucency",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"thicknessTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"refractionTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"indexOfRefraction",void 0);F([X()],Fn.prototype,"_volumeIndexOfRefraction",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"volumeIndexOfRefraction",null);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"invertRefractionY",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"linkRefractionWithTransparency",void 0);F([X()],Fn.prototype,"minimumThickness",void 0);F([X()],Fn.prototype,"maximumThickness",void 0);F([X()],Fn.prototype,"useThicknessAsDepth",void 0);F([br()],Fn.prototype,"tintColor",void 0);F([X()],Fn.prototype,"tintColorAtDistance",void 0);F([X()],Fn.prototype,"dispersion",void 0);F([br()],Fn.prototype,"diffusionDistance",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"useMaskFromThicknessTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"refractionIntensityTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"translucencyIntensityTexture",void 0);F([br()],Fn.prototype,"translucencyColor",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"translucencyColorTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Fn.prototype,"useGltfStyleTextures",void 0);const kI={effect:null,subMesh:null};class Bhe extends _s{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Pr extends aa{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t,i=!1){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new mt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Pr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Re.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Re(0,0,0),this._albedoColor=new Re(1,1,1),this._reflectivityColor=new Re(1,1,1),this._reflectionColor=new Re(1,1,1),this._emissiveColor=new Re(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Pr.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new no(16),this._globalAmbientColor=new Re(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1;const r=this.getScene().getEngine();r.isWebGPU&&!i&&!Pr.ForceGLSL&&(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new zt(r,void 0,void 0,this.name,!0),this._shaderLanguage=1),this.brdf=new Ic(this),this.clearCoat=new Xo(this),this.iridescence=new Uc(this),this.anisotropy=new Wx(this),this.sheen=new L0(this),this.subSurface=new Fn(this),this.detailMap=new C_(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Je.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Hz(this.getScene()),this.prePassConfiguration=new hZ}get hasRenderTargetTextures(){return Je.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===Pr.PBRMATERIAL_OPAQUE||this._transparencyMode===Pr.PBRMATERIAL_ALPHATEST||((e=this.subSurface)==null?void 0:e.disableAlphaBlending)}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()}needAlphaTesting(){var e;return this._forceAlphaTest?!0:(e=this.subSurface)!=null&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Pr.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Pr.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Bhe(this._eventInfo.defineNames));const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=this.getScene(),o=a.getEngine();if(n._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&Je.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&Je.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&Je.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const f=this._getReflectionTexture();if(f&&Je.ReflectionTextureEnabled){if(!f.isReadyOrNotBlocking())return!1;if(f.irradianceTexture){if(!f.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!f.sphericalPolynomial&&((d=f.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&Je.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&Je.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Je.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&Je.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&Je.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||n._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent($.NormalKind)&&(e.createNormals(!0),fe.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const l=t.effect,c=n._areLightsDisposed;let u=this._prepareEffect(e,n,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),h=!1;if(u)if(this._onEffectCreatedObservable&&(kI.effect=u,kI.subMesh=t,this._onEffectCreatedObservable.notifyObservers(kI)),this.allowShaderHotSwapping&&l&&!u.isReady()){if(u=l,n.markAsUnprocessed(),h=this.isFrozen,c)return n._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(u,n,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(n._renderId=a.getRenderId(),r._wasPreviouslyReady=!h,r._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i=null,r=null,n=null,a=null,o){if(this._prepareDefines(e,t,n,a,o),!t.isDirty)return null;t.markAsProcessed();const c=this.getScene().getEngine(),u=new oa;let h=0;t.USESPHERICALINVERTEX&&u.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&u.addFallback(h,"FOG"),t.SPECULARAA&&u.addFallback(h,"SPECULARAA"),t.POINTSIZE&&u.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&u.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&u.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&u.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&u.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&u.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&u.addFallback(h++,"TANGENT"),t.BUMP&&u.addFallback(h++,"BUMP"),h=Zo(t,u,this._maxSimultaneousLights,h++),t.SPECULARTERM&&u.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&u.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&u.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&u.addFallback(h++,"LIGHTMAP"),t.NORMAL&&u.addFallback(h++,"NORMAL"),t.AMBIENT&&u.addFallback(h++,"AMBIENT"),t.EMISSIVE&&u.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&u.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&u.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const d=[$.PositionKind];t.NORMAL&&d.push($.NormalKind),t.TANGENT&&d.push($.TangentKind);for(let A=1;A<=6;++A)t["UV"+A]&&d.push(`uv${A===1?"":A}`);t.VERTEXCOLOR&&d.push($.ColorKind),Vu(d,e,t,u),Ya(d,t),dz(d,e,t),Zw(d,e,t);let f="pbr";const p=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],m=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=d,this._eventInfo.samplers=m,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),hZ.AddUniforms(p),fo(p),lr&&(lr.PrepareUniforms(p,t),lr.PrepareSamplers(m,t)),po({uniformsNames:p,uniformBuffersNames:g,samplers:m,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const y={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,g,m,t,d,y));const v=t.toString(),x=c.createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:g,samplers:m,defines:v,fallbacks:u,onCompiled:i,onError:r,indexParameters:_,processFinalCode:y.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>UWe),void 0),Ue(()=>Promise.resolve().then(()=>qWe),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>iKe),void 0),Ue(()=>Promise.resolve().then(()=>mKe),void 0)]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,n=!1){const a=this.getScene(),o=a.getEngine();du(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,qw(a,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(mz(a,t,this.canRenderToMRT&&!l),OJ(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let c=1;c<=6;++c)t["MAINUV"+c]=!1;if(a.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&Je.DiffuseTextureEnabled?(rn(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Je.AmbientTextureEnabled?(rn(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Je.OpacityTextureEnabled?(rn(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const c=this._getReflectionTexture();if(c&&Je.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=c.gammaSpace,t.RGBDREFLECTION=c.isRGBD,t.LODINREFLECTIONALPHA=c.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=c.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=c.coordinatesMode===xe.INVCUBIC_MODE,t.REFLECTIONMAP_3D=c.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!c.invertZ:c.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,c.coordinatesMode){case xe.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case xe.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case xe.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case xe.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case xe.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case xe.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case xe.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case xe.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case xe.CUBIC_MODE:case xe.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!c.boundingBoxSize;break}c.coordinatesMode!==xe.SKYBOX_MODE&&(c.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):c.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&Je.LightmapTextureEnabled?(rn(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Je.EmissiveTextureEnabled?(rn(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Je.SpecularTextureEnabled?(this._metallicTexture?(rn(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(rn(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(rn(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(rn(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?rn(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&Je.BumpTextureEnabled&&!this._disableBumpMap?(rn(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Je.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&Je.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Pr.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Pr.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,t.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(Kc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent($.NormalKind),t.DEBUGMODE=this._debugMode),Hc(a,o,this,t,!!i,r,n),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Na(e,t,!0,!0,!0,this._transparencyMode!==Pr.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;const a=new Bhe(this._eventInfo.defineNames),o=this._prepareEffect(e,a,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(kI.effect=o,kI.subMesh=null,this._onEffectCreatedObservable.notifyObservers(kI)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var h,d,f;const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);const o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=this._mustRebind(r,a,i,t.visibility);ql(t,this._activeEffect,this.prePassConfiguration);let c=null;const u=this._uniformBuffer;if(l){if(this.bindViewProjection(a),c=this._getReflectionTexture(),!u.useUbo||!this.isFrozen||!u.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){if(this._albedoTexture&&Je.DiffuseTextureEnabled&&(u.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),sn(this._albedoTexture,u,"albedo")),this._ambientTexture&&Je.AmbientTextureEnabled&&(u.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),sn(this._ambientTexture,u,"ambient")),this._opacityTexture&&Je.OpacityTextureEnabled&&(u.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),sn(this._opacityTexture,u,"opacity")),c&&Je.ReflectionTextureEnabled){if(u.updateMatrix("reflectionMatrix",c.getReflectionTextureMatrix()),u.updateFloat2("vReflectionInfos",c.level,0),c.boundingBoxSize){const p=c;u.updateVector3("vReflectionPosition",p.boundingBoxPosition),u.updateVector3("vReflectionSize",p.boundingBoxSize)}if(this.realTimeFiltering){const p=c.getSize().width;u.updateFloat2("vReflectionFilteringInfo",p,At.Log2(p))}if(!n.USEIRRADIANCEMAP){const p=c.sphericalPolynomial;if(n.USESPHERICALFROMREFLECTIONMAP&&p)if(n.SPHERICAL_HARMONICS){const m=p.preScaledHarmonics;u.updateVector3("vSphericalL00",m.l00),u.updateVector3("vSphericalL1_1",m.l1_1),u.updateVector3("vSphericalL10",m.l10),u.updateVector3("vSphericalL11",m.l11),u.updateVector3("vSphericalL2_2",m.l2_2),u.updateVector3("vSphericalL2_1",m.l2_1),u.updateVector3("vSphericalL20",m.l20),u.updateVector3("vSphericalL21",m.l21),u.updateVector3("vSphericalL22",m.l22)}else u.updateFloat3("vSphericalX",p.x.x,p.x.y,p.x.z),u.updateFloat3("vSphericalY",p.y.x,p.y.y,p.y.z),u.updateFloat3("vSphericalZ",p.z.x,p.z.y,p.z.z),u.updateFloat3("vSphericalXX_ZZ",p.xx.x-p.zz.x,p.xx.y-p.zz.y,p.xx.z-p.zz.z),u.updateFloat3("vSphericalYY_ZZ",p.yy.x-p.zz.x,p.yy.y-p.zz.y,p.yy.z-p.zz.z),u.updateFloat3("vSphericalZZ",p.zz.x,p.zz.y,p.zz.z),u.updateFloat3("vSphericalXY",p.xy.x,p.xy.y,p.xy.z),u.updateFloat3("vSphericalYZ",p.yz.x,p.yz.y,p.yz.z),u.updateFloat3("vSphericalZX",p.zx.x,p.zx.y,p.zx.z)}u.updateFloat3("vReflectionMicrosurfaceInfos",c.getSize().width,c.lodGenerationScale,c.lodGenerationOffset)}this._emissiveTexture&&Je.EmissiveTextureEnabled&&(u.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),sn(this._emissiveTexture,u,"emissive")),this._lightmapTexture&&Je.LightmapTextureEnabled&&(u.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),sn(this._lightmapTexture,u,"lightmap")),Je.SpecularTextureEnabled&&(this._metallicTexture?(u.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),sn(this._metallicTexture,u,"reflectivity")):this._reflectivityTexture&&(u.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),sn(this._reflectivityTexture,u,"reflectivity")),this._metallicReflectanceTexture&&(u.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),sn(this._metallicReflectanceTexture,u,"metallicReflectance")),this._reflectanceTexture&&n.REFLECTANCE&&(u.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),sn(this._reflectanceTexture,u,"reflectance")),this._microSurfaceTexture&&(u.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),sn(this._microSurfaceTexture,u,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&Je.BumpTextureEnabled&&!this._disableBumpMap&&(u.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),sn(this._bumpTexture,u,"bump"),r._mirroredCameraPosition?u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&u.updateFloat("pointSize",this.pointSize),n.METALLICWORKFLOW){ts.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,ts.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,u.updateColor4("vReflectivityColor",ts.Color3[0],1);const p=((h=this.subSurface)==null?void 0:h._indexOfRefraction)??1.5,m=1,g=Math.pow((p-m)/(p+m),2);this._metallicReflectanceColor.scaleToRef(g*this._metallicF0Factor,ts.Color3[0]);const _=this._metallicF0Factor;u.updateColor4("vMetallicReflectanceFactors",ts.Color3[0],_)}else u.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);u.updateColor3("vEmissiveColor",Je.EmissiveTextureEnabled?this._emissiveColor:Re.BlackReadOnly),u.updateColor3("vReflectionColor",this._reflectionColor),!n.SS_REFRACTION&&((d=this.subSurface)!=null&&d._linkRefractionWithTransparency)?u.updateColor4("vAlbedoColor",this._albedoColor,1):u.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,u.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),u.updateColor3("vAmbientColor",this._globalAmbientColor),u.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&Je.DiffuseTextureEnabled&&u.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Je.AmbientTextureEnabled&&u.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Je.OpacityTextureEnabled&&u.setTexture("opacitySampler",this._opacityTexture),c&&Je.ReflectionTextureEnabled&&(n.LODBASEDMICROSFURACE?u.setTexture("reflectionSampler",c):(u.setTexture("reflectionSampler",c._lodTextureMid||c),u.setTexture("reflectionSamplerLow",c._lodTextureLow||c),u.setTexture("reflectionSamplerHigh",c._lodTextureHigh||c)),n.USEIRRADIANCEMAP&&u.setTexture("irradianceSampler",c.irradianceTexture)),n.ENVIRONMENTBRDF&&u.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Je.EmissiveTextureEnabled&&u.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Je.LightmapTextureEnabled&&u.setTexture("lightmapSampler",this._lightmapTexture),Je.SpecularTextureEnabled&&(this._metallicTexture?u.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&u.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&u.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&n.REFLECTANCE&&u.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&u.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&Je.BumpTextureEnabled&&!this._disableBumpMap&&u.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Xa(this._activeEffect,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&hu(r,t,this._activeEffect,n,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==gt.FOGMODE_NONE||c||this.subSurface.refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),ml(r,t,this._activeEffect,!0),n.NUM_MORPH_INFLUENCERS&&I0(t,this._activeEffect),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(a,n.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),uo(n,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),u.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var t;if(!((t=this.subSurface)!=null&&t.isScatteringEnabled))return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){var i,r,n,a,o,l,c,u,h,d,f,p;this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(n=this._opacityTexture)==null||n.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._metallicTexture)==null||l.dispose(),(c=this._reflectivityTexture)==null||c.dispose(),(u=this._bumpTexture)==null||u.dispose(),(h=this._lightmapTexture)==null||h.dispose(),(d=this._metallicReflectanceTexture)==null||d.dispose(),(f=this._reflectanceTexture)==null||f.dispose(),(p=this._microSurfaceTexture)==null||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Pr.PBRMATERIAL_OPAQUE=Ye.MATERIAL_OPAQUE;Pr.PBRMATERIAL_ALPHATEST=Ye.MATERIAL_ALPHATEST;Pr.PBRMATERIAL_ALPHABLEND=Ye.MATERIAL_ALPHABLEND;Pr.PBRMATERIAL_ALPHATESTANDBLEND=Ye.MATERIAL_ALPHATESTANDBLEND;Pr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;Pr.LIGHTFALLOFF_PHYSICAL=0;Pr.LIGHTFALLOFF_GLTF=1;Pr.LIGHTFALLOFF_STANDARD=2;Pr.ForceGLSL=!1;F([Jme()],Pr.prototype,"_imageProcessingConfiguration",void 0);F([Fe("_markAllSubMeshesAsMiscDirty")],Pr.prototype,"debugMode",void 0);class Lt extends Pr{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Pr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Pr.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Pr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Pr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Pr.LIGHTFALLOFF_GLTF:this._lightFalloff=Pr.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t,i=!1){super(e,t,i),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=Lt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Re.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Re(0,0,0),this.albedoColor=new Re(1,1,1),this.reflectivityColor=new Re(1,1,1),this.reflectionColor=new Re(1,1,1),this.emissiveColor=new Re(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=Hz(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const r=qe.Clone(()=>new Lt(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const r=qe.Parse(()=>new Lt(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ye._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}Lt.PBRMATERIAL_OPAQUE=Pr.PBRMATERIAL_OPAQUE;Lt.PBRMATERIAL_ALPHATEST=Pr.PBRMATERIAL_ALPHATEST;Lt.PBRMATERIAL_ALPHABLEND=Pr.PBRMATERIAL_ALPHABLEND;Lt.PBRMATERIAL_ALPHATESTANDBLEND=Pr.PBRMATERIAL_ALPHATESTANDBLEND;Lt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Pr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"directIntensity",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"emissiveIntensity",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"environmentIntensity",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"specularIntensity",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"disableBumpMap",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"albedoTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"ambientTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"ambientTextureStrength",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],Lt.prototype,"opacityTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"reflectionTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"emissiveTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"reflectivityTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"metallicTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"metallic",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"roughness",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"metallicF0Factor",void 0);F([br(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"metallicReflectanceColor",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"metallicReflectanceTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"reflectanceTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"microSurfaceTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"bumpTexture",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty",null)],Lt.prototype,"lightmapTexture",void 0);F([br("ambient"),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"ambientColor",void 0);F([br("albedo"),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"albedoColor",void 0);F([br("reflectivity"),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"reflectivityColor",void 0);F([br("reflection"),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"reflectionColor",void 0);F([br("emissive"),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"emissiveColor",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"microSurface",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useLightmapAsShadowmap",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],Lt.prototype,"useAlphaFromAlbedoTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],Lt.prototype,"forceAlphaTest",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesAndMiscDirty")],Lt.prototype,"alphaCutOff",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useSpecularOverAlpha",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useRoughnessFromMetallicTextureGreen",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useMetallnessFromMetallicTextureBlue",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useAmbientInGrayScale",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);F([X()],Lt.prototype,"usePhysicalLightFalloff",null);F([X()],Lt.prototype,"useGLTFLightFalloff",null);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useRadianceOverAlpha",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useObjectSpaceNormalMap",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useParallax",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useParallaxOcclusion",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"parallaxScaleBias",void 0);F([X(),Fe("_markAllSubMeshesAsLightsDirty")],Lt.prototype,"disableLighting",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"forceIrradianceInFragment",void 0);F([X(),Fe("_markAllSubMeshesAsLightsDirty")],Lt.prototype,"maxSimultaneousLights",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"invertNormalMapX",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"invertNormalMapY",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"twoSidedLighting",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useAlphaFresnel",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useLinearAlphaFresnel",void 0);F([Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"environmentBRDFTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"forceNormalForward",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"enableSpecularAntiAliasing",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useHorizonOcclusion",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Lt.prototype,"useRadianceOcclusion",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Lt.prototype,"unlit",void 0);F([X(),Fe("_markAllSubMeshesAsMiscDirty")],Lt.prototype,"applyDecalMapAfterDetailMap",void 0);ve("BABYLON.PBRMaterial",Lt);class eUe{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,r){const n=t.getEngine();let a,o=!1,l=1e3;if(Array.isArray(e))for(let c=0;c1)&&t.generateMipMaps,n._unpackFlipY(a.isCompressed),Ks.UploadDDSLevels(n,t,u,a,o,6,-1,c),!a.isFourCC&&a.mipmapCount===1?n.generateMipMapsForCubemap(t):l=a.mipmapCount-1}else{const c=e;a=Ks.GetDDSInfo(c),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new hg),o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(a.isCompressed),Ks.UploadDDSLevels(n,t,c,a,o,6),!a.isFourCC&&a.mipmapCount===1?n.generateMipMapsForCubemap(t,!1):l=a.mipmapCount-1}n._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){const r=Ks.GetDDSInfo(e),n=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&Math.max(r.width,r.height)>>r.mipmapCount-1===1;i(r.width,r.height,n,r.isFourCC,()=>{Ks.UploadDDSLevels(t.getEngine(),t,e,r,n,1)})}}const $4t=Object.freeze(Object.defineProperty({__proto__:null,_DDSTextureLoader:eUe},Symbol.toStringTag,{value:"Module"}));class tUe{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,n){if(Array.isArray(e))return;const a=lee(e);if(a){t.width=a.width,t.height=a.width;try{uee(t,a),m1e(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},o=>{n==null||n("Can not upload environment levels",o)})}catch(o){n==null||n("Can not upload environment file",o)}}else n&&n("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}const Z4t=Object.freeze(Object.defineProperty({__proto__:null,_ENVTextureLoader:tUe},Symbol.toStringTag,{value:"Module"}));class wu{constructor(e,t){if(this.data=e,this.isInvalid=!1,!wu.IsValid(e)){this.isInvalid=!0,fe.Error("texture missing KTX identifier");return}const i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),a=r.getUint32(0,!0)===67305985;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),this.glType!==0){fe.Error("only compressed formats currently supported"),this.isInvalid=!0;return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){fe.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){fe.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){fe.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=wu.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case wu.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case wu.TEX_2D:case wu.COMPRESSED_3D:case wu.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=wu.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,n=this.pixelHeight;const a=t?this.numberOfMipmapLevels:1;for(let o=0;o=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===49&&t[6]===49&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}}wu.HEADER_LEN=12+13*4;wu.COMPRESSED_2D=0;wu.COMPRESSED_3D=1;wu.TEX_2D=2;wu.TEX_3D=3;class iUe{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map(t=>({workerPromise:Promise.resolve(t),idle:!0}))}dispose(){for(const e of this._workerInfos)e.workerPromise.then(t=>{t.terminate()});this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{const r=this._pendingActions.shift();r?this._execute(e,r):e.idle=!0})})}}class rD extends iUe{constructor(e,t,i=rD.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(a=>{a.terminate()});const n=this._workerInfos.indexOf(e);n!==-1&&this._workerInfos.splice(n,1)},this._options.idleTimeElapsedBeforeRelease))})})}}rD.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var khe;(function(s){s[s.ETC1S=0]="ETC1S",s[s.UASTC4x4=1]="UASTC4x4"})(khe||(khe={}));var cP;(function(s){s[s.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",s[s.BC7_RGBA=1]="BC7_RGBA",s[s.BC3_RGBA=2]="BC3_RGBA",s[s.BC1_RGB=3]="BC1_RGB",s[s.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",s[s.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",s[s.ETC2_RGBA=6]="ETC2_RGBA",s[s.ETC1_RGB=7]="ETC1_RGB",s[s.RGBA32=8]="RGBA32",s[s.R8=9]="R8",s[s.RG8=10]="RG8"})(cP||(cP={}));var Uhe;(function(s){s[s.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",s[s.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",s[s.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",s[s.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",s[s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",s[s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",s[s.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",s[s.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",s[s.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",s[s.RGBA8Format=32856]="RGBA8Format",s[s.R8Format=33321]="R8Format",s[s.RG8Format=33323]="RG8Format"})(Uhe||(Uhe={}));function _Z(s,e){const t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;s&&(s.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=s.wasmUASTCToASTC),s.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=s.wasmUASTCToBC7),s.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=s.wasmUASTCToRGBA_UNORM),s.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=s.wasmUASTCToRGBA_SRGB),s.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=s.wasmUASTCToR8_UNORM),s.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=s.wasmUASTCToRG8_UNORM),s.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=s.jsMSCTranscoder),s.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=s.wasmMSCTranscoder),s.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=s.wasmZSTDDecoder)),e&&(e.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmBinary=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmBinary=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(t.MSCTranscoder.JSModule=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(t.MSCTranscoder.WasmBinary=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmBinary=e.wasmZSTDDecoder))}function q4t(s){typeof s>"u"&&typeof KTX2DECODER<"u"&&(s=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;i&&(i.jsDecoderModule&&typeof s>"u"&&(importScripts(i.jsDecoderModule),s=KTX2DECODER),_Z(i)),t.data.wasmBinaries&&_Z(void 0,{...t.data.wasmBinaries,jsDecoderModule:s}),e=new s.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{s.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{const r=[];for(let n=0;n{postMessage({action:"decoded",success:!1,msg:i})});break}}}function J4t(s,e,t){return new Promise((i,r)=>{const n=o=>{s.removeEventListener("error",n),s.removeEventListener("message",a),r(o)},a=o=>{o.data.action==="init"&&(s.removeEventListener("error",n),s.removeEventListener("message",a),i(s))};s.addEventListener("error",n),s.addEventListener("message",a),s.postMessage({action:"init",urls:t,wasmBinaries:e})})}class rUe{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[cP.BC1_RGB,cP.BC3_RGBA],yes:{transcodeFormat:cP.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class Zs{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(Zs._WorkerPoolPromise||Zs._DecoderModulePromise)return;const t={jsDecoderModule:Me.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Me.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Me.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Me.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Me.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Me.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Me.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Me.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Me.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Me.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?Zs._WorkerPoolPromise=new Promise(i=>{const r=`${_Z}(${q4t})()`,n=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new rD(e,()=>J4t(new Worker(n),void 0,t)))}):typeof Zs._KTX2DecoderModule>"u"?Zs._DecoderModulePromise=Me.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(Zs._KTX2DecoderModule=KTX2DECODER,Zs._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,Zs._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,_Z(t,Zs._KTX2DecoderModule),new Zs._KTX2DecoderModule.KTX2Decoder)):(Zs._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,Zs._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Zs._DecoderModulePromise=Promise.resolve(new Zs._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=Zs.DefaultNumWorkers){var r;this._engine=e;const i=typeof t=="object"&&t.workerPool||Zs.WorkerPool;if(i)Zs._WorkerPoolPromise=Promise.resolve(i);else{typeof t=="object"?Zs._KTX2DecoderModule=(r=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:r.jsDecoderModule:typeof KTX2DECODER<"u"&&(Zs._KTX2DecoderModule=KTX2DECODER);const n=typeof t=="number"?t:t.numWorkers??Zs.DefaultNumWorkers;Zs._Initialize(n)}}_uploadAsync(e,t,i){const r=this._engine.getCaps(),n={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(Zs._WorkerPoolPromise)return Zs._WorkerPoolPromise.then(a=>new Promise((o,l)=>{a.push((c,u)=>{const h=p=>{c.removeEventListener("error",h),c.removeEventListener("message",d),l(p),u()},d=p=>{if(p.data.action==="decoded"){if(c.removeEventListener("error",h),c.removeEventListener("message",d),!p.data.success)l({message:p.data.msg});else try{this._createTexture(p.data.decodedData,t,i),o()}catch(m){l({message:m})}u()}};c.addEventListener("error",h),c.addEventListener("message",d),c.postMessage({action:"setDefaultDecoderOptions",options:Zs.DefaultDecoderOptions._getKTX2DecoderOptions()});const f=new Uint8Array(e.byteLength);f.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),c.postMessage({action:"decode",data:f,caps:n,options:i},[f.buffer])})}));if(Zs._DecoderModulePromise)return Zs._DecoderModulePromise.then(a=>(Zs.DefaultDecoderOptions.isDirty&&(Zs._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=Zs.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((o,l)=>{a.decode(e,r).then(c=>{this._createTexture(c,t),o()}).catch(c=>{l({message:c})})})));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let n=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,n=!1;break}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let a=0;a=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===50&&t[6]===48&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}}Zs.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null};Zs.DefaultNumWorkers=Zs.GetDefaultNumWorkers();Zs.DefaultDecoderOptions=new rUe;function eyt(s){switch(s){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}class sUe{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const n=t.getEngine(),a=new wu(e,6),o=a.numberOfMipmapLevels>1&&t.generateMipMaps;n._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,n._setCubeMapTextureParams(t,o,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(wu.IsValid(e)){t._invertVScale=!t.invertY;const n=new wu(e,1),a=eyt(n.glInternalFormat);a?(t.format=a,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=n.glInternalFormat,i(n.pixelWidth,n.pixelHeight,t.generateMipMaps,!0,()=>{n.uploadLevels(t,t.generateMipMaps)},n.isInvalid)}else Zs.IsValid(e)?new Zs(t.getEngine())._uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},a=>{fe.Warn(`Failed to load KTX2 texture data: ${a.message}`),i(0,0,!1,!1,()=>{},!0)}):(fe.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}const tyt=Object.freeze(Object.defineProperty({__proto__:null,_KTXTextureLoader:sUe},Symbol.toStringTag,{value:"Module"}));class nw extends Dl{constructor(e,t,i){super(e,D.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=Pe.Identity(),this._referencedPosition=new D,this._trackingState=0,this.onXRCameraInitializedObservable=new Ae,this.onBeforeCameraTeleport=new Ae,this.onAfterCameraTeleport=new Ae,this.onTrackingStateChanged=new Ae,this.compensateOnFirstFrame=!0,this._rotate180=new Pe(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new Pe,this.cameraRigMode=Nt.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add(()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()})}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new uc(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new uc(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,Pe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=se.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),Pe.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(0);return}const t=e.emulatedPosition?1:2;if(this._setTrackingState(t),(this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ)&&this._updateDepthNearFar(),e.transform){const i=e.transform.orientation;if(e.transform.orientation.x===void 0)return;const r=e.transform.position;this._referencedPosition.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(i.x,i.y,i.z,i.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((i,r)=>{var h;const n=this.rigCameras[r];!n.isLeftCamera&&!n.isRightCamera&&(i.eye==="right"?n._isRightCamera=!0:i.eye==="left"&&(n._isLeftCamera=!0));const a=this.getScene().customRenderTargets;for(let d=0;de;){const t=this.rigCameras.pop();t&&t.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=se.Matrix[0],t=se.Matrix[1],i=se.Matrix[2];he.ComposeToRef(nw._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),he.ComposeToRef(nw._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const r=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}}nw._ScaleReadOnly=D.One();class pee{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new Ae,this.onStateChangedObservable=new Ae,this.state=3,this.sessionManager=new Dz(e),this.camera=new nw("webxr",e,this.sessionManager),this.featuresManager=new Yn(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new pee(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(3),t.dispose(),i})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),(e=this._spectatorCamera)==null||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){var n,a,o,l;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(0),t!=="viewer"&&t!=="local"&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),e==="immersive-ar"&&t!=="unbounded"&&fe.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);const c={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(wr.LAYERS)){const u=await i.initializeXRLayerAsync(this.sessionManager.session);c.baseLayer=u}return this.sessionManager.updateRenderState(c),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!((a=(n=this._nonVRCamera)==null?void 0:n.inputs)!=null&&a.attachedToElement),(o=this._nonVRCamera)==null||o.detachControl(),this._scene.activeCamera=this.camera,e!=="immersive-ar"?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),(l=Ge.audioEngine)==null||l._resumeAudioContextOnStateChange(),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==1&&this._setState(1),this.camera.rigCameras.forEach(u=>{u.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),e!=="immersive-ar"&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(3)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(2)}),this.sessionManager}catch(c){throw fe.Log(c),fe.Log(c.message),this._setState(3),c}}exitXRAsync(){return this.state!==2?Promise.resolve():(this._setState(1),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const i=1/(e!=null&&e.fps?e.fps:1e3)*1e3,r=e!=null&&e.preferredCameraIndex?e==null?void 0:e.preferredCameraIndex:0,n=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const a=()=>{this.state===2?(this._spectatorCamera=new Vx("webxr-spectator",D.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new Pe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(n),this._scene.onAfterRenderCameraObservable.add(o=>{o===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===1&&(this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=null)};this.onStateChangedObservable.add(a),a()}else this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class id{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new Ae,this.onButtonStateChangedObservable=new Ae}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return this._axesIndices.length!==0}isButton(){return this._buttonIndex!==-1}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const r=e.buttons[this._buttonIndex];if(!r)return;this._currentValue!==r.value&&(this.changes.value={current:r.value,previous:this._currentValue},t=!0,this._currentValue=r.value),this._touched!==r.touched&&(this.changes.touched={current:r.touched,previous:this._touched},t=!0,this._touched=r.touched),this._pressed!==r.pressed&&(this.changes.pressed={current:r.pressed,previous:this._pressed},t=!0,this._pressed=r.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}id.BUTTON_TYPE="button";id.SQUEEZE_TYPE="squeeze";id.THUMBSTICK_TYPE="thumbstick";id.TOUCHPAD_TYPE="touchpad";id.TRIGGER_TYPE="trigger";var zhe;(function(s){s[s.Clean=0]="Clean",s[s.Stop=1]="Stop",s[s.Sync=2]="Sync",s[s.NoSync=3]="NoSync"})(zhe||(zhe={}));function iyt(s){return!!s.name}const nUe=new Ae,ix={};let zne=!1;function M1e(){return ix[".babylon"]}function R1e(s){const e=ix[s];return e||(fe.Warn("Unable to find a plugin to load "+s+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),M1e())}function ryt(s){return!!ix[s]}function syt(s){for(const e in ix){const t=ix[e].plugin;if(t.canDirectLoad&&t.canDirectLoad(s))return ix[e]}return M1e()}function nyt(s){const e=s.indexOf("?");e!==-1&&(s=s.substring(0,e));const t=s.lastIndexOf("."),i=s.substring(t,s.length).toLowerCase();return R1e(i)}function ayt(s){return s.substr(0,5)==="data:"?s.substr(5):null}function I1e(s,e,t){let r="Unable to load from "+(s.rawData?"binary data":s.url);return e?r+=`: ${e}`:t&&(r+=`: ${t}`),r}function P1e(s,e,t,i,r,n,a,o,l){var v,x,A,b;const c=ayt(s.url);if(s.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const u=a?R1e(a):c?syt(s.url):nyt(s.url);if(((v=l==null?void 0:l[u.plugin.name])==null?void 0:v.enabled)===!1)throw new Error(`The '${u.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(s.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";const h=((A=(x=u.plugin).createPlugin)==null?void 0:A.call(x,l??{}))??u.plugin;if(!h)throw`The loader plugin corresponding to the '${a}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(nUe.notifyObservers(h),c&&(h.canDirectLoad&&h.canDirectLoad(s.url)||!uz(s.url))){if(h.directLoad){const C=h.directLoad(e,c);C instanceof Promise?C.then(T=>{t(h,T)}).catch(T=>{r("Error in directLoad of _loadData: "+T,T)}):t(h,C)}else t(h,c);return h}const d=u.isBinary,f=(C,T)=>{if(e.isDisposed){r("Scene has been disposed");return}t(h,C,T)};let p=null,m=!1;(b=h.onDisposeObservable)==null||b.add(()=>{m=!0,p&&(p.abort(),p=null),n()});const g=()=>{if(m)return;const C=(T,w)=>{r(T==null?void 0:T.statusText,w)};if(!h.loadFile&&s.rawData)throw"Plugin does not support loading ArrayBufferView.";p=h.loadFile?h.loadFile(e,s.rawData||s.file||s.url,s.rootUrl,f,i,d,C,o):e._loadFile(s.file||s.url,f,i,!0,d,C)},_=e.getEngine();let y=_.enableOfflineSupport;if(y){let C=!1;for(const T of e.disableOfflineSupportExceptionRules)if(T.test(s.url)){C=!0;break}y=!C}return y&&Ge.OfflineProviderFactory?e.offlineProvider=Ge.OfflineProviderFactory(s.url,g,_.disableManifestCheck):g(),h}function w1e(s,e){let t,i,r=null,n=null;if(!e)t=s,i=Me.GetFilename(s),s=Me.GetFolderPath(s);else if(iyt(e))t=`file:${e.name}`,i=e.name,r=e;else if(ArrayBuffer.isView(e))t="",i=gh(),n=e;else if(e.startsWith("data:"))t=e,i="";else if(s){const a=e;if(a.substr(0,1)==="/")return Me.Error("Wrong sceneFilename parameter"),null;t=s+a,i=a}else t=e,i=Me.GetFilename(e),s=Me.GetFolderPath(e);return{url:t,rootUrl:s,name:i,file:r,rawData:n}}function sD(s){if(typeof s.extensions=="string"){const e=s.extensions;ix[e.toLowerCase()]={plugin:s,isBinary:!1}}else{const e=s.extensions;Object.keys(e).forEach(t=>{ix[t.toLowerCase()]={plugin:s,isBinary:e[t].isBinary}})}}function aUe(s,e,t="",i=Rt.LastCreatedScene,r=null,n=null,a=null,o=null,l="",c={}){if(!i)return fe.Error("No scene available to import mesh to"),null;const u=w1e(e,t);if(!u)return null;const h={};i.addPendingData(h);const d=()=>{i.removePendingData(h)},f=(g,_)=>{const y=I1e(u,g,_);a?a(i,y,new R0(y,x_.SceneLoaderError,_)):fe.Error(y),d()},p=n?g=>{try{n(g)}catch(_){f("Error in onProgress callback: "+_,_)}}:void 0,m=(g,_,y,v,x,A,b,C)=>{if(i.importedMeshesFiles.push(u.url),r)try{r(g,_,y,v,x,A,b,C)}catch(T){f("Error in onSuccess callback: "+T,T)}i.removePendingData(h)};return P1e(u,i,(g,_,y)=>{if(g.rewriteRootURL&&(u.rootUrl=g.rewriteRootURL(u.rootUrl,y)),g.importMesh){const v=g,x=[],A=[],b=[];if(!v.importMesh(s,i,_,u.rootUrl,x,A,b,f))return;i.loadingPluginName=g.name,m(x,A,b,[],[],[],[],[])}else g.importMeshAsync(s,i,_,u.rootUrl,p,u.name).then(x=>{i.loadingPluginName=g.name,m(x.meshes,x.particleSystems,x.skeletons,x.animationGroups,x.transformNodes,x.geometries,x.lights,x.spriteManagers)}).catch(x=>{f(x.message,x)})},p,f,d,o,l,c)}function oyt(s,e,t,i,r,n,a,o){return new Promise((l,c)=>{aUe(s,e,t,i,(u,h,d,f,p,m,g,_)=>{l({meshes:u,particleSystems:h,skeletons:d,animationGroups:f,transformNodes:p,geometries:m,lights:g,spriteManagers:_})},r,(u,h,d)=>{c(d||new Error(h))},n,a,o)})}function oUe(s,e="",t=Rt.LastCreatedEngine,i=null,r=null,n=null,a=null,o="",l={}){return t?D1e(s,e,new gt(t),i,r,n,a,o,l):(Me.Error("No engine available"),null)}function lyt(s,e,t){const{rootUrl:i="",onProgress:r,pluginExtension:n,name:a,pluginOptions:o}=t??{};return lUe(i,s,e,r,n,a,o)}function lUe(s,e,t,i,r,n,a){return new Promise((o,l)=>{oUe(s,e,t,c=>{o(c)},i,(c,u,h)=>{l(h||new Error(u))},r,n,a)})}function D1e(s,e="",t=Rt.LastCreatedScene,i=null,r=null,n=null,a=null,o="",l={}){if(!t)return fe.Error("No scene available to append to"),null;const c=w1e(s,e);if(!c)return null;const u={};t.addPendingData(u);const h=()=>{t.removePendingData(u)};Eo.ShowLoadingScreen&&!zne&&(zne=!0,t.getEngine().displayLoadingUI(),t.executeWhenReady(()=>{t.getEngine().hideLoadingUI(),zne=!1}));const d=(m,g)=>{const _=I1e(c,m,g);n?n(t,_,new R0(_,x_.SceneLoaderError,g)):fe.Error(_),h()},f=r?m=>{try{r(m)}catch(g){d("Error in onProgress callback",g)}}:void 0,p=()=>{if(i)try{i(t)}catch(m){d("Error in onSuccess callback",m)}t.removePendingData(u)};return P1e(c,t,(m,g)=>{if(m.load){if(!m.load(t,g,c.rootUrl,d))return;t.loadingPluginName=m.name,p()}else m.loadAsync(t,g,c.rootUrl,f,c.name).then(()=>{t.loadingPluginName=m.name,p()}).catch(y=>{d(y.message,y)})},f,d,h,a,o,l)}async function cyt(s,e,t){const{rootUrl:i="",onProgress:r,pluginExtension:n,name:a,pluginOptions:o}=t??{};await cUe(i,s,e,r,n,a,o)}function cUe(s,e,t,i,r,n,a){return new Promise((o,l)=>{D1e(s,e,t,c=>{o(c)},i,(c,u,h)=>{l(h||new Error(u))},r,n,a)})}function L1e(s,e="",t=Rt.LastCreatedScene,i=null,r=null,n=null,a=null,o="",l={}){if(!t)return fe.Error("No scene available to load asset container to"),null;const c=w1e(s,e);if(!c)return null;const u={};t.addPendingData(u);const h=()=>{t.removePendingData(u)},d=(m,g)=>{const _=I1e(c,m,g);n?n(t,_,new R0(_,x_.SceneLoaderError,g)):fe.Error(_),h()},f=r?m=>{try{r(m)}catch(g){d("Error in onProgress callback",g)}}:void 0,p=m=>{if(i)try{i(m)}catch(g){d("Error in onSuccess callback",g)}t.removePendingData(u)};return P1e(c,t,(m,g)=>{if(m.loadAssetContainer){const y=m.loadAssetContainer(t,g,c.rootUrl,d);if(!y)return;y.populateRootNodes(),t.loadingPluginName=m.name,p(y)}else m.loadAssetContainerAsync?m.loadAssetContainerAsync(t,g,c.rootUrl,f,c.name).then(y=>{y.populateRootNodes(),t.loadingPluginName=m.name,p(y)}).catch(y=>{d(y.message,y)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},f,d,h,a,o,l)}function uyt(s,e,t){const{rootUrl:i="",onProgress:r,pluginExtension:n,name:a,pluginOptions:o}=t??{};return uUe(i,s,e,r,n,a,o)}function uUe(s,e,t,i,r,n,a){return new Promise((o,l)=>{L1e(s,e,t,c=>{o(c)},i,(c,u,h)=>{l(h||new Error(u))},r,n,a)})}function hUe(s,e="",t=Rt.LastCreatedScene,i=!0,r=0,n=null,a=null,o=null,l=null,c=null,u="",h={}){if(!t){fe.Error("No scene available to load animations to");return}if(i){for(const m of t.animatables)m.reset();t.stopAllAnimations(),t.animationGroups.slice().forEach(m=>{m.dispose()}),t.getNodes().forEach(m=>{m.animations&&(m.animations=[])})}else switch(r){case 0:t.animationGroups.slice().forEach(p=>{p.dispose()});break;case 1:t.animationGroups.forEach(p=>{p.stop()});break;case 2:t.animationGroups.forEach(p=>{p.reset(),p.restart()});break;case 3:break;default:fe.Error("Unknown animation group loading mode value '"+r+"'");return}const d=t.animatables.length;L1e(s,e,t,p=>{p.mergeAnimationsTo(t,t.animatables.slice(d),n),p.dispose(),t.onAnimationFileImportedObservable.notifyObservers(t),a&&a(t)},o,l,c,u,h)}async function hyt(s,e,t){const{rootUrl:i="",overwriteAnimations:r,animationGroupLoadingMode:n,targetConverter:a,onProgress:o,pluginExtension:l,name:c,pluginOptions:u}=t??{};await dUe(i,s,e,r,n,a,o,l,c,u)}function dUe(s,e,t,i,r,n,a,o,l,c){return new Promise((u,h)=>{hUe(s,e,t,i,r,n,d=>{u(d)},a,(d,f,p)=>{h(p||new Error(f))},o,l,c)})}class Ys{static get ForceFullSceneLoadingForIncremental(){return Eo.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Eo.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Eo.ShowLoadingScreen}static set ShowLoadingScreen(e){Eo.ShowLoadingScreen=e}static get loggingLevel(){return Eo.loggingLevel}static set loggingLevel(e){Eo.loggingLevel=e}static get CleanBoneMatrixWeights(){return Eo.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Eo.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return M1e()}static GetPluginForExtension(e){return R1e(e).plugin}static IsPluginForExtensionAvailable(e){return ryt(e)}static RegisterPlugin(e){sD(e)}static ImportMesh(e,t,i,r,n,a,o,l,c){return aUe(e,t,i,r,n,a,o,l,c)}static ImportMeshAsync(e,t,i,r,n,a,o){return oyt(e,t,i,r,n,a,o)}static Load(e,t,i,r,n,a,o,l){return oUe(e,t,i,r,n,a,o,l)}static LoadAsync(e,t,i,r,n,a){return lUe(e,t,i,r,n,a)}static Append(e,t,i,r,n,a,o,l){return D1e(e,t,i,r,n,a,o,l)}static AppendAsync(e,t,i,r,n,a){return cUe(e,t,i,r,n,a)}static LoadAssetContainer(e,t,i,r,n,a,o,l){return L1e(e,t,i,r,n,a,o,l)}static LoadAssetContainerAsync(e,t,i,r,n,a){return uUe(e,t,i,r,n,a)}static ImportAnimations(e,t,i,r,n,a,o,l,c,u,h){hUe(e,t,i,r,n,a,o,l,c,u,h)}static ImportAnimationsAsync(e,t,i,r,n,a,o,l,c,u,h){return dUe(e,t,i,r,n,a,l,u,h)}}Ys.NO_LOGGING=0;Ys.MINIMAL_LOGGING=1;Ys.SUMMARY_LOGGING=2;Ys.DETAILED_LOGGING=3;Ys.OnPluginActivatedObservable=nUe;class lT{constructor(e,t,i,r,n=!1,a){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=n,this._controllerCache=a,this._initComponent=o=>{if(!o)return;const l=this.layout.components[o],c=l.type,u=l.gamepadIndices.button,h=[];l.gamepadIndices.xAxis!==void 0&&l.gamepadIndices.yAxis!==void 0&&h.push(l.gamepadIndices.xAxis,l.gamepadIndices.yAxis),this.components[o]=new id(o,c,u,h)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new Ae,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(t=>this.components[t]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?fe.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{const n=a=>{e?this._getGenericParentMesh(a):this._setRootMesh(a),this._processLoadedModel(a),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const a=this._controllerCache.filter(o=>o.filename===t.filename&&o.path===t.path);if(a[0]){a[0].meshes.forEach(o=>o.setEnabled(!0)),n(a[0].meshes);return}}Ys.ImportMesh("",t.path,t.filename,this.scene,a=>{this._controllerCache&&this._controllerCache.push({...t,meshes:a}),n(a)},null,(a,o)=>{fe.Log(o),fe.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(o)})})}updateFromXRFrame(e){this.getComponentIds().forEach(t=>this.getComponent(t).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(i=>i.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(i=>i.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const r=i?t*.5+.5:t;Pe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),D.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Ee(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=Pe.FromEulerAngles(0,Math.PI,0)}}class aw extends lT{constructor(e,t,i){super(e,dyt[i],t,i),this.profileId=aw.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Ee(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=Pe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}aw.ProfileId="generic-trigger";const dyt={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class fUe extends lT{constructor(e,t,i,r,n){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,n),this._repositoryUrl=r,this.controllerCache=n,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=Ys.IsPluginForExtensionAvailable(".glb");return e||fe.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=this.layout.components[t];this._buttonMeshMapping[t]={mainMesh:this._getChildByName(this.rootMesh,i.rootNodeName),states:{}},Object.keys(i.visualResponses).forEach(r=>{const n=i.visualResponses[r];if(n.valueNodeProperty==="transform")this._buttonMeshMapping[t].states[r]={valueMesh:this._getChildByName(this.rootMesh,n.valueNodeName),minMesh:this._getChildByName(this.rootMesh,n.minNodeName),maxMesh:this._getChildByName(this.rootMesh,n.maxNodeName)};else{const a=i.type===id.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:n.valueNodeName;if(this._buttonMeshMapping[t].states[r]={valueMesh:this._getChildByName(this.rootMesh,a)},i.type===id.TOUCHPAD_TYPE&&!this._touchDots[r]){const o=kc(r+"dot",{diameter:.0015,segments:8},this.scene);o.material=new et(r+"mat",this.scene),o.material.diffuseColor=Re.Red(),o.parent=this._buttonMeshMapping[t].states[r].valueMesh||null,o.isVisible=!1,this._touchDots[r]=o}}})})}_setRootMesh(e){this.rootMesh=new Ee(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;i{const i=this.getComponent(t);if(!i.hasChanges)return;const r=this._buttonMeshMapping[t],n=this.layout.components[t];Object.keys(n.visualResponses).forEach(a=>{const o=n.visualResponses[a];let l=i.value;if(o.componentProperty==="xAxis"?l=i.axes.x:o.componentProperty==="yAxis"&&(l=i.axes.y),o.valueNodeProperty==="transform")this._lerpTransform(r.states[a],l,o.componentProperty!=="button");else{const c=r.states[a].valueMesh;c&&(c.isVisible=i.touched||i.pressed),this._touchDots[a]&&(this._touchDots[a].isVisible=i.touched||i.pressed)}})})}}const Vne=[];class ll{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const r=[];if(i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0):r.push("oculus-touch-v2");break}const n=r.indexOf("windows-mixed-reality");if(n!==-1&&r.splice(n,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),this.UseOnlineRepository){const a=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,o=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return a.call(this,r,e,t).catch(()=>o.call(this,r,e,t))}else return this._LoadProfilesFromAvailableControllers(r,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Me.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){Vne.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),Vne.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(r=>{for(let n=0;n(this._ProfileLoadingPromises[r]||(this._ProfileLoadingPromises[r]=Me.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${r}/profile.json`,!1).then(n=>JSON.parse(n))),this._ProfileLoadingPromises[r])).then(r=>new fUe(i,t,r,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:Vne))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew aw(e,s.gamepad,s.handedness));ll.DefaultFallbacks();let fyt=0;class pUe{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new D,this._disposed=!1,this.onDisposeObservable=new Ae,this.onMeshLoadedObservable=new Ae,this.onMotionControllerInitObservable=new Ae,this._uniqueId=`controller-${fyt++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Ee(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new Pe,this.inputSource.gripSpace&&(this.grip=new Ee(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new Pe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&ll.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(r=>{this.motionController=r,this.onMotionControllerInitObservable.notifyObservers(r),!this._options.doNotLoadControllerMesh&&!this.motionController._doNotLoadControllerMesh&&this.motionController.loadModel().then(n=>{var a;n&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(o=>o.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&((a=this.motionController)==null||a.dispose())})},()=>{Me.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;D.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,r){const n=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=n,n){const a=n.transform.position;this.pointer.position.set(a.x,a.y,a.z).scaleInPlace(r.worldScalingFactor);const o=n.transform.orientation;this.pointer.rotationQuaternion.set(o.x,o.y,o.z,o.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(r.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const a=e.getPose(this.inputSource.gripSpace,t);if(a){const o=a.transform.position,l=a.transform.orientation;this.grip.position.set(o.x,o.y,o.z).scaleInPlace(r.worldScalingFactor),this.grip.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(r.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class mUe{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new Ae,this.onControllerRemovedObservable=new Ae,this._onInputSourcesChange=r=>{this._addAndRemoveControllers(r.added,r.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(r=>r.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(r=>{r.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(r=>{this.controllers.forEach(n=>{n.updateFromXRFrame(r,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)})}),this._options.customControllersRepositoryURL&&(ll.BaseRepositoryUrl=this._options.customControllersRepositoryURL),ll.UseOnlineRepository=!this._options.disableOnlineControllerRepository,ll.UseOnlineRepository)try{ll.UpdateProfilesList().catch(()=>{ll.UseOnlineRepository=!1})}catch{ll.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(a=>a.inputSource);for(const a of e)if(i.indexOf(a)===-1){const o=new pUe(this.xrSessionManager.scene,a,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(o),this.onControllerAddedObservable.notifyObservers(o)}const r=[],n=[];this.controllers.forEach(a=>{t.indexOf(a.inputSource)===-1?r.push(a):n.push(a)}),this.controllers=r,n.forEach(a=>{this.onControllerRemovedObservable.notifyObservers(a),a.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),ll.ClearControllerCache()}}class gl{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){var t;!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&((t=this._xrSessionManager.enabledFeatures)==null?void 0:t.indexOf(e))===-1&&fe.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new Ae,this.onFeatureDetachObservable=new Ae}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(!this._xrSessionManager.enabledFeatures)fe.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");else if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName)===-1)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,t=>this._onXRFrame(t)),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class eg extends gl{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:r,selectionMesh:n}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&i.grip?i.grip:i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:r,selectionMesh:n,meshUnderPointer:null,pick:null,tmpRay:new $i(new D,new D),disabledByNearInteraction:!1,id:eg._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(i);case"gaze":return this._attachGazeMode(i);case"screen":case"transient-pointer":return this._attachScreenRayMode(i)}},this._controllers={},this._tmpVectorForPickCompare=new D,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Re(.9,.9,.9),this.laserPointerDefaultColor=new Re(.7,.7,.7),this.selectionMeshDefaultColor=new Re(.8,.8,.8),this.selectionMeshPickedColor=new Re(.3,.3,1),this._identityMatrix=he.Identity(),this._screenCoordinatesRef=D.Zero(),this._viewportRef=new uc(0,0,0,0),this._scene=this._xrSessionManager.scene,this._options.lookAndPickMode===void 0&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)},!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new $i(new D,new D),disabledByNearInteraction:!1,id:eg._IdCounter++},this._attachGazeMode()}return!0}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0):!1}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{var l;const i=this._controllers[t];if(this._options.lookAndPickMode&&((l=i.xrController)==null?void 0:l.inputSource.targetRayMode)!=="transient-pointer")return;if(!this._options.enablePointerSelectionOnAllControllers&&t!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}i.laserPointer.isVisible=this.displayLaserPointer;let r;if(i.xrController)r=this._options.forceGripIfAvailable&&i.xrController.grip?i.xrController.grip.position:i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay,this._options.forceGripIfAvailable);else if(i.webXRCamera)r=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay);else return;if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&r){const c=this._xrSessionManager.scene,u=this._options.xrInput.xrCamera;u&&(u.viewport.toGlobalToRef(c.getEngine().getRenderWidth()/u.rigCameras.length,c.getEngine().getRenderHeight(),this._viewportRef),D.ProjectToRef(r,this._identityMatrix,u.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),typeof this._screenCoordinatesRef.x=="number"&&typeof this._screenCoordinatesRef.y=="number"&&!isNaN(this._screenCoordinatesRef.x)&&!isNaN(this._screenCoordinatesRef.y)&&this._screenCoordinatesRef.x!==1/0&&this._screenCoordinatesRef.y!==1/0&&(c.pointerX=this._screenCoordinatesRef.x,c.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let n=null;this._utilityLayerScene&&(n=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const a=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);!n||!n.hit?i.pick=a:!a||!a.hit||n.distance{if(t.pick){if(this._augmentPointerInit(c,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,a.isVisible=!1,t.pick.hit)if(this._pickingMoved(n,t.pick))l&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,c)),l=!1,o=0;else if(o>i/10&&(a.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,c),l=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,c),a.isVisible=!1;else{const u=1-o/i;a.scaling.set(u,u,u)}else l=!1,o=0;this._scene.simulatePointerMove(t.pick,c),n=t.pick}}),this._options.renderingGroupId!==void 0&&(a.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&l&&(this._scene.simulatePointerUp(t.pick,c),t.finalPointerUpTriggered=!0),a.dispose()})}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),!(!t.pick||this._options.disablePointerUpOnTouchOut&&i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){const r=n=>{this._options.overrideButtonId&&(t.selectionComponent=n.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=n.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(a=>{if(a.changes.pressed){const o=a.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),o?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(o&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const l=this._controllers[this._attachedController];l&&l.pointerDownTriggered&&!l.finalPointerUpTriggered&&(this._augmentPointerInit(i,l.id,l.screenCoordinates),this._scene.simulatePointerUp(new Ko,{pointerId:l.id,pointerType:"xr"}),l.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}})};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=a=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)})},n=a=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)})};t.eventListeners={selectend:n,selectstart:r},this._xrSessionManager.session.addEventListener("selectstart",r),this._xrSessionManager.session.addEventListener("selectend",n)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(D.Dot(e,t.direction)){const r=t.eventListeners&&t.eventListeners[i];r&&this._xrSessionManager.session.removeEventListener(i,r)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const i={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new Ko,i),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const i=Object.keys(this._controllers);i.length?this._attachedController=i[0]:this._attachedController=""}}catch{Me.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||is.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():ou("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const r=new et("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const n=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():ug("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);n.bakeCurrentTransformIntoVertices(),n.isPickable=!1,n.isVisible=!1;const a=new et("targetMat",t);return a.specularColor=Re.Black(),a.emissiveColor=this.selectionMeshDefaultColor,a.backFaceCulling=!1,n.material=a,this._options.renderingGroupId!==void 0&&(i.renderingGroupId=this._options.renderingGroupId,n.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:n}}_pickingMoved(e,t){var n;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(n=e.pickedPoint)==null||n.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=(this._options.gazeModePointerMovedFactor||1)*.01*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}eg._IdCounter=200;eg.Name=wr.POINTER_SELECTION;eg.Version=1;Yn.AddWebXRFeature(eg.Name,(s,e)=>()=>new eg(s,e),eg.Version,!0);var ee;(function(s){s[s.Float=1]="Float",s[s.Int=2]="Int",s[s.Vector2=4]="Vector2",s[s.Vector3=8]="Vector3",s[s.Vector4=16]="Vector4",s[s.Color3=32]="Color3",s[s.Color4=64]="Color4",s[s.Matrix=128]="Matrix",s[s.Object=256]="Object",s[s.AutoDetect=1024]="AutoDetect",s[s.BasedOnInput=2048]="BasedOnInput",s[s.All=4095]="All"})(ee||(ee={}));var be;(function(s){s[s.Vertex=1]="Vertex",s[s.Fragment=2]="Fragment",s[s.Neutral=4]="Neutral",s[s.VertexAndFragment=3]="VertexAndFragment"})(be||(be={}));class tMe{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return this.shaderLanguage===1?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===be.Fragment;this.shaderLanguage===1?i?this.compilationString=` ${t?`//Entry point `:""}@fragment fn main(input: FragmentInputs) -> FragmentOutputs { ${this.compilationString}`:this.compilationString=` ${t?`//Entry point `:""}@vertex fn main(input: VertexInputs) -> FragmentInputs{ ${this.compilationString}`:this.compilationString=` ${t?`//Entry point `:""}void main(void) { ${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` ${t?`//Constants `:""}${this._constantDeclaration} ${this.compilationString}`);let r="";for(const n in this.functions)r+=this.functions[n]+` `;if(this.compilationString=` ${r} ${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} ${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} ${this._injectAtEnd}`),this.compilationString=`${this.compilationString} }`,this.sharedData.varyingDeclaration&&(this.compilationString=` ${t?`//Varyings `:""}${this.sharedData.varyingDeclaration} ${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` ${t?`//Samplers `:""}${this._samplerDeclaration} ${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` ${t?`//Uniforms `:""}${this._uniformDeclaration} ${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` ${t?`//Attributes `:""}${this._attributeDeclaration} ${this.compilationString}`),this.shaderLanguage!==1){this.compilationString=`precision highp float; `+this.compilationString,this.compilationString=`#if defined(WEBGL2) || defined(WEBGPU) precision highp sampler2DArray; #endif `+this.compilationString,i&&(this.compilationString=`#if defined(PREPASS)\r #extension GL_EXT_draw_buffers : require\r layout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r highp vec4 gl_FragColor;\r #endif\r `+this.compilationString);for(const n in this.extensions){const a=this.extensions[n];this.compilationString=` ${a} ${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),this.sharedData.variableNames[e]===void 0?(this.sharedData.variableNames[e]=0,e==="output"||e==="texture"?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return this.sharedData.defineNames[e]===void 0?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e,t="",i=!1){(this.samplers.indexOf(e)<0||i)&&(t&&(this._samplerDeclaration+=`#if ${t} `),this.shaderLanguage===1?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler; `,this._samplerDeclaration+=`var ${e}: texture_2d; `):this._samplerDeclaration+=`uniform sampler2D ${e}; `,t&&(this._samplerDeclaration+=`#endif `),i||this.samplers.push(e))}_emitCubeSampler(e,t="",i=!1){(this.samplers.indexOf(e)<0||i)&&(t&&(this._samplerDeclaration+=`#if ${t} `),this.shaderLanguage===1?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler; `,this._samplerDeclaration+=`var ${e}: texture_cube; `):this._samplerDeclaration+=`uniform samplerCube ${e}; `,t&&(this._samplerDeclaration+=`#endif `),i||this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; `,this.samplers.push(e))}_getGLType(e){switch(e){case ee.Float:return"float";case ee.Int:return"int";case ee.Vector2:return"vec2";case ee.Color3:case ee.Vector3:return"vec3";case ee.Color4:case ee.Vector4:return"vec4";case ee.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===1;switch(e){case ee.Float:return t?"f32":"float";case ee.Int:return t?"i32":"int";case ee.Vector2:return t?"vec2f":"vec2";case ee.Color3:case ee.Vector3:return t?"vec3f":"vec3";case ee.Color4:case ee.Vector4:return t?"vec4f":"vec4";case ee.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} ${t} #endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` `+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){const r=de.GetIncludesShadersStore(this.shaderLanguage);if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] `;let n=r[e]+` `;if(this.sharedData.emitComments&&(n=t+` `+n),!i)return n;if(i.replaceStrings)for(let a=0;a${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] `:this.functions[n]=`#include<${e}>${i!=null&&i.substitutionVars?"("+(i==null?void 0:i.substitutionVars)+")":""} `,this.sharedData.emitComments&&(this.functions[n]=t+` `+this.functions[n]);return}if(this.functions[n]=a[e],this.sharedData.emitComments&&(this.functions[n]=t+` `+this.functions[n]),i.removeIfDef&&(this.functions[n]=this.functions[n].replace(/^\s*?#ifdef.+$/gm,""),this.functions[n]=this.functions[n].replace(/^\s*?#endif.*$/gm,""),this.functions[n]=this.functions[n].replace(/^\s*?#else.*$/gm,""),this.functions[n]=this.functions[n].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[n]=this.functions[n].replace(/\s*?attribute .+?;/g,` `)),i.removeUniforms&&(this.functions[n]=this.functions[n].replace(/\s*?uniform .*?;/g,` `)),i.removeVaryings&&(this.functions[n]=this.functions[n].replace(/\s*?(varying|in) .+?;/g,` `)),i.replaceStrings)for(let o=0;o")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),(t,i,r,n)=>`select(${n}, ${r}, ${i})`)}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),(t,i,r)=>`((${i})%(${r}))`)}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;(i=t.exec(e))!==null;){const r=i[1],n=i[2],o=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${r}(${o}) -> ${n}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=this._convertOutParametersToWGSL(e),e=e.replace(/\[\*\]/g,"*"),e=this._convertFunctionsToWGSL(e),e=e.replace(/\s->\svoidnull/g,""),e=e.replace(/dFdx/g,"dpdx"),e=e.replace(/dFdy/g,"dpdy"),e}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),(t,i,r,n)=>`${i} ? ${r} : ${n}`)}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),e=this._convertTernaryOperandsToGLSL(e),e}}class pyt{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";!this.checks.emitVertex&&!this.allowEmptyVertexProgram&&(e+=`NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value. `),this.checks.emitFragment||(e+=`NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value. `);for(const t of this.checks.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. `;if(e)throw`Build of NodeMaterial failed: `+e}}var Vhe;(function(s){s[s.Compatible=0]="Compatible",s[s.TypeIncompatible=1]="TypeIncompatible",s[s.TargetIncompatible=2]="TargetIncompatible",s[s.HierarchyIssue=3]="HierarchyIssue"})(Vhe||(Vhe={}));var Ghe;(function(s){s[s.Input=0]="Input",s[s.Output=1]="Output"})(Ghe||(Ghe={}));class o6{static AreEquivalentTypes(e,t){switch(e){case ee.Vector3:{if(t===ee.Color3)return!0;break}case ee.Vector4:{if(t===ee.Color4)return!0;break}case ee.Color3:{if(t===ee.Vector3)return!0;break}case ee.Color4:{if(t===ee.Vector4)return!0;break}}return!1}get _connectedPoint(){return this._connectedPointBackingField}set _connectedPoint(e){var t;this._connectedPointBackingField!==e&&((t=this._connectedPointTypeChangedObserver)==null||t.remove(),this._updateTypeDependentState(()=>this._connectedPointBackingField=e),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add(()=>{this._notifyTypeChanged()})))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){var t;this._typeConnectionSourceBackingField!==e&&((t=this._typeConnectionSourceTypeChangedObserver)==null||t.remove(),this._updateTypeDependentState(()=>this._typeConnectionSourceBackingField=e),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add(()=>{this._notifyTypeChanged()})))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState(()=>this._defaultConnectionPointTypeBackingField=e)}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){var t;this._linkedConnectionSourceBackingField!==e&&((t=this._linkedConnectionSourceTypeChangedObserver)==null||t.remove(),this._updateTypeDependentState(()=>this._linkedConnectionSourceBackingField=e),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add(()=>{this._notifyTypeChanged()})))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:(!this._enforceAssociatedVariableName||!this._associatedVariableName)&&this._connectedPoint?this._connectedPoint.declarationVariableName:this._associatedVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:(!this._enforceAssociatedVariableName||!this._associatedVariableName)&&this._connectedPoint?this._connectedPoint.associatedVariableName:this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===ee.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===ee.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState(()=>this._type=e)}get target(){return!this._prioritizeVertex||!this._ownerBlock?this._target:this._target!==be.VertexAndFragment?this._target:this._ownerBlock.target===be.Fragment?be.Fragment:be.Vertex}set target(e){this._target=e}get isConnected(){return this.connectedPoint!==null||this.hasEndpoints}get isConnectedToInputBlock(){return this.connectedPoint!==null&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return this._endpoints.length===0?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===be.Vertex||(e.ownerBlock.target===be.Neutral||e.ownerBlock.target===be.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===be.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===be.Vertex||e.target===be.Vertex||(e.ownerBlock.target===be.Neutral||e.ownerBlock.target===be.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===be.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===be.Fragment||(e.ownerBlock.target===be.Neutral||e.ownerBlock.target===be.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPointBackingField=null,this._endpoints=new Array,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=ee.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new Ae,this.onDisconnectionObservable=new Ae,this.onTypeChangedObservable=new Ae,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=be.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===0}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===be.Fragment){if(i.target===be.Vertex)return 2;for(const a of i.outputs)if(a.ownerBlock.target!=be.Neutral&&a.isConnectedInVertexShader)return 2}if(this.type!==e.type&&e.innerType!==ee.AutoDetect)return o6.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1||e._acceptedConnectionPointType&&o6.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?0:1;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return 1;let r=i,n=t;return this.direction===0&&(r=t,n=i),r.isAnAncestorOf(n)?3:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this),this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class qt{get name(){return this._name}get codeIsReady(){return this._codeIsReady}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter(i=>i.name===e);return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter(i=>i.name===e);return t.length?t[0]:null}constructor(e,t=be.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this._codeIsReady=!0,this.onCodeIsReadyObservable=new Ae,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===be.Neutral,this._isFinalMerger=i,this._isInput=this.getClassName()==="InputBlock",this._isTeleportOut=this.getClassName()==="NodeMaterialTeleportOutBlock",this._isTeleportIn=this.getClassName()==="NodeMaterialTeleportInBlock",this._name=e,this.uniqueId=hz.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===be.Neutral}initialize(e){}bind(e,t,i,r){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return t.indexOf(".")===-1&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,n){return n=n??new o6(e,this,0),n.type=t,n.isOptional=i,r&&(n.target=r),this._inputs.push(n),this}registerOutput(e,t,i,r){return r=r??new o6(e,this,1),r.type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===ee.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===be.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return t===-1||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(this._outputs.length===0)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){const n=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&n&&i.canConnectTo(n))i.connectTo(n),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,n){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput)||this.target===be.Vertex?!1:!!((this.target===be.VertexAndFragment||this.target===be.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);const n=t._vertexState!=null,a=e._buildTarget===be.Vertex&&e.target!==be.VertexAndFragment;if(n&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==be.VertexAndFragment&&a)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const o=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+o.declarationVariableName,o.type)){const c=t.shaderLanguage===1?"vertexOutputs.":"";t._vertexState.compilationString+=`${c}${"v_"+o.declarationVariableName} = ${o.associatedVariableName}; `}const l=t.shaderLanguage===1?"fragmentInputs.":"";i.associatedVariableName=l+"v_"+o.declarationVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const i of this._outputs)i.associatedVariableName||(i.associatedVariableName=e._getFreeVariableName(i.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==be.Neutral&&(!(i.target&this.target)||!(i.target&e.target)))continue;const r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&fe.Log(`${e.target===be.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case be.Vertex:e.sharedData.checks.emitVertex=!0;break;case be.Fragment:e.sharedData.checks.emitFragment=!0;break}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` //${this.name} `),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const r of i.endpoints){const n=r.ownerBlock;n&&n.target&e.target&&t.indexOf(n)!==-1&&this._processBuild(n,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; ${e}.visibleOnFrame = ${this.visibleOnFrame}; ${e}.target = ${this.target}; `}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,e.indexOf(this._codeVariableName)!==-1){let n=0;do n++,this._codeVariableName=i+n;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let r=` // ${this.getClassName()} `;this.comments&&(r+=`// ${this.comments} `),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); `,r+=this._dumpPropertiesCode();for(const n of this.inputs){if(!n.isConnected)continue;const o=n.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(r+=o._dumpCode(e,t))}for(const n of this.outputs)if(n.hasEndpoints)for(const a of n.endpoints){const o=a.ownerBlock;o&&t.indexOf(o)===-1&&(r+=o._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(e.indexOf(this)!==-1)return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,n=r.ownerBlock;t+=n._dumpCodeForOutputConnections(e),t+=`${n._codeVariableName}.${n._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); `}return t}clone(e,t=""){const i=this.serialize(),r=Xn(i.customType);if(r){const n=new r;return n._deserialize(i,e,t),n}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,r){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((r,n)=>{r.displayName&&(this.inputs[n].displayName=r.displayName),r.isExposedOnFrame&&(this.inputs[n].isExposedOnFrame=r.isExposedOnFrame,this.inputs[n].exposedPortPosition=r.exposedPortPosition)}),i&&i.forEach((r,n)=>{r.displayName&&(this.outputs[n].displayName=r.displayName),r.isExposedOnFrame&&(this.outputs[n].isExposedOnFrame=r.isExposedOnFrame,this.outputs[n].exposedPortPosition=r.exposedPortPosition)})}dispose(){this.onCodeIsReadyObservable.clear();for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class vZ extends qt{constructor(e){super(e,be.Neutral),this.complementW=1,this.complementZ=0,this.target=be.Vertex,this.registerInput("vector",ee.AutoDetect),this.registerInput("transform",ee.Matrix),this.registerOutput("output",ee.Vector4),this.registerOutput("xyz",ee.Vector3),this._inputs[0].onConnectionObservable.add(t=>{if(t.ownerBlock.isInput){const i=t.ownerBlock;(i.name==="normal"||i.name==="tangent")&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,r=e._getShaderType(ee.Vector4),n=e._getShaderType(ee.Vector3);if(t.connectedPoint){if(this.complementW===0){const a=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",a),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.shaderLanguage===1?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz); `:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName}); `,e.compilationString+=`#ifdef NONUNIFORMSCALING `,e.compilationString+=`${o} = transposeMat3(inverseMat3(${o})); `,e.compilationString+=`#endif `,t.connectedPoint.type){case ee.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${n}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); `;break;case ee.Vector3:case ee.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); `;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); `;break}}else{const a=i.associatedVariableName;switch(t.connectedPoint.type){case ee.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${a} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); `;break;case ee.Vector3:case ee.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${a} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); `;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${a} * ${t.associatedVariableName}; `;break}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz; `)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=e.complementZ!==void 0?e.complementZ:0,this.complementW=e.complementW!==void 0?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; `;return e+=`${this._codeVariableName}.complementW = ${this.complementW}; `,e}}ve("BABYLON.TransformBlock",vZ);class HB extends qt{constructor(e){super(e,be.Vertex,!0),this.registerInput("vector",ee.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const i of e)if(i.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=e.shaderLanguage===1;if(e.shaderLanguage===1?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName}; `:e.compilationString+=`gl_Position = ${t.associatedVariableName}; `,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)){e._emitUniformFromString("logarithmicDepthConstant",ee.Float),e._emitVaryingFromString("vFragmentDepth",ee.Float);const r=i?"vertexOutputs.vFragmentDepth":"vFragmentDepth",n=i?"uniforms.":"",a=i?"vertexOutputs.position":"gl_Position";e.compilationString+=`${r} = 1.0 + ${a}.w; `,e.compilationString+=`${a}.z = log2(max(0.000001, ${r})) * ${n}logarithmicDepthConstant; `}return this}}ve("BABYLON.VertexOutputBlock",HB);var Whe;(function(s){s[s.Boolean=0]="Boolean",s[s.Float=1]="Float",s[s.Int=2]="Int",s[s.Vector2=3]="Vector2",s[s.List=4]="List"})(Whe||(Whe={}));function Jt(s,e=0,t="PROPERTIES",i){return(r,n)=>{let a=r._propStore;a||(a=[],r._propStore=a),a.push({propertyName:n,displayName:s,type:e,groupName:t,options:i??{}})}}class dv extends qt{constructor(e){super(e,be.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",ee.Color4,!0),this.registerInput("rgb",ee.AutoDetect,!0),this.registerInput("a",ee.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&uo(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,r=this.a,n=e.shaderLanguage===1;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",ee.Float),e._emitVaryingFromString("vFragmentDepth",ee.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const a=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",a);let o="gl_FragColor";e.shaderLanguage===1&&(e.compilationString+=`var fragmentOutputsColor : vec4;\r `,o="fragmentOutputsColor");const l=e._getShaderType(ee.Vector4);if(t.connectedPoint)r.isConnected?e.compilationString+=`${o} = ${l}(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); `:e.compilationString+=`${o} = ${t.associatedVariableName}; `;else if(i.connectedPoint){let c="1.0";r.connectedPoint&&(c=r.associatedVariableName),i.connectedPoint.type===ee.Float?e.compilationString+=`${o} = ${l}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${c}); `:e.compilationString+=`${o} = ${l}(${i.associatedVariableName}, ${c}); `}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);if(e.compilationString+=`#ifdef ${this._linearDefineName} `,e.compilationString+=`${o} = toLinearSpace(${o}); `,e.compilationString+=`#endif `,e.compilationString+=`#ifdef ${this._gammaDefineName} `,e.compilationString+=`${o} = toGammaSpace(${o}); `,e.compilationString+=`#endif `,e.shaderLanguage===1&&(e.compilationString+=`#if !defined(PREPASS)\r `,e.compilationString+=`fragmentOutputs.color = fragmentOutputsColor;\r `,e.compilationString+=`#endif\r `),this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth){const c=n?"input.vFragmentDepth":"vFragmentDepth",u=n?"uniforms.":"",h=n?"fragmentOutputs.fragDepth":"gl_FragDepthEXT";e.compilationString+=`${h} = log2(${c}) * ${u}logarithmicDepthConstant * 0.5; `}return e.compilationString+=`#if defined(PREPASS)\r `,e.compilationString+=`${n?"fragmentOutputs.fragData0":"gl_FragData[0]"} = ${o};\r `,e.compilationString+=`#endif\r `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; `,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; `,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; `,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}F([Jt("Convert to gamma space",0,"PROPERTIES",{notifiers:{update:!0}})],dv.prototype,"convertToGammaSpace",void 0);F([Jt("Convert to linear space",0,"PROPERTIES",{notifiers:{update:!0}})],dv.prototype,"convertToLinearSpace",void 0);F([Jt("Use logarithmic depth",0,"PROPERTIES")],dv.prototype,"useLogarithmicDepth",void 0);ve("BABYLON.FragmentOutputBlock",dv);var mr;(function(s){s[s.World=1]="World",s[s.View=2]="View",s[s.Projection=3]="Projection",s[s.ViewProjection=4]="ViewProjection",s[s.WorldView=5]="WorldView",s[s.WorldViewProjection=6]="WorldViewProjection",s[s.CameraPosition=7]="CameraPosition",s[s.FogColor=8]="FogColor",s[s.DeltaTime=9]="DeltaTime",s[s.CameraParameters=10]="CameraParameters",s[s.MaterialAlpha=11]="MaterialAlpha"})(mr||(mr={}));var w1;(function(s){s[s.None=0]="None",s[s.Time=1]="Time",s[s.RealTime=2]="RealTime",s[s.MouseInfo=3]="MouseInfo"})(w1||(w1={}));const myt={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Gne={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},iMe={particle_texturemask:!0};class nr extends qt{get type(){if(this._type===ee.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=ee.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=ee.Vector2,this._type;case"Vector3":return this._type=ee.Vector3,this._type;case"Vector4":return this._type=ee.Vector4,this._type;case"Color3":return this._type=ee.Color3,this._type;case"Color4":return this._type=ee.Color4,this._type;case"Matrix":return this._type=ee.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=ee.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=ee.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=ee.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=ee.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case mr.World:case mr.WorldView:case mr.WorldViewProjection:case mr.View:case mr.ViewProjection:case mr.Projection:return this._type=ee.Matrix,this._type;case mr.CameraPosition:return this._type=ee.Vector3,this._type;case mr.FogColor:return this._type=ee.Color3,this._type;case mr.DeltaTime:case mr.MaterialAlpha:return this._type=ee.Float,this._type;case mr.CameraParameters:return this._type=ee.Vector4,this._type}}return this._type}constructor(e,t=be.Vertex,i=ee.AutoDetect){super(e,t,!1),this._mode=3,this._animationType=w1.None,this._prefix="",this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new Ae,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return this.isAttribute?!0:super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=1,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===ee.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=0,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=0}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===3}get isUniform(){return this._mode===0}set isUniform(e){this._mode=e?0:3,this.associatedVariableName=""}get isAttribute(){return this._mode===1}set isAttribute(e){this._mode=e?1:3,this.associatedVariableName=""}get isVarying(){return this._mode===2}set isVarying(e){this._mode=e?2:3,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=0,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case w1.Time:{this.type===ee.Float&&(this.value+=e.getAnimationRatio()*.01);break}case w1.RealTime:{this.type===ee.Float&&(this.value=(Or.Now-e.getEngine().startTime)/1e3);break}case w1.MouseInfo:{if(this.type===ee.Vector4){const t=e._inputManager._originMouseEvent;if(t){const i=t.offsetX,r=t.offsetY,n=t.buttons&1?1:0,a=t.buttons&2?1:0;this.value=new mt(i,r,n,a)}else this.value=new mt(0,0,0,0)}break}}}_emitDefine(e){return e[0]==="!"?`#ifndef ${e.substring(1)} `:`#ifdef ${e} `}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case ee.Float:this.value=0;break;case ee.Vector2:this.value=we.Zero();break;case ee.Vector3:this.value=D.Zero();break;case ee.Vector4:this.value=mt.Zero();break;case ee.Color3:this.value=Re.White();break;case ee.Color4:this.value=new Ze(1,1,1,1);break;case ee.Matrix:this.value=he.Identity();break}}_emitConstant(e){switch(this.type){case ee.Float:return`${e._emitFloat(this.value)}`;case ee.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case ee.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case ee.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case ee.Color3:return ts.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&ts.Color3[0].toGammaSpaceToRef(ts.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ts.Color3[0].toLinearSpaceToRef(ts.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${ts.Color3[0].r}, ${ts.Color3[0].g}, ${ts.Color3[0].b})`;case ee.Color4:return ts.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&ts.Color4[0].toGammaSpaceToRef(ts.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ts.Color4[0].toLinearSpaceToRef(ts.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${ts.Color4[0].r}, ${ts.Color4[0].g}, ${ts.Color4[0].b}, ${ts.Color4[0].a})`}return""}get _noContextSwitch(){return Gne[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(e.constants.indexOf(this.associatedVariableName)!==-1)return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)}; `;return}if(e.uniforms.indexOf(this.associatedVariableName)!==-1)return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);e.shaderLanguage===1?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i}; `,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName}; `,t&&(e._uniformDeclaration+=`#endif `);const r=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case mr.WorldView:r.needWorldViewMatrix=!0;break;case mr.WorldViewProjection:r.needWorldViewProjectionMatrix=!0;break}else this._animationType!==w1.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=myt[this.name]??this.name,this.target===be.Vertex&&e._vertexState){Gne[this.name]?iMe[this.name]?(e._emitUniformFromString(this.declarationVariableName,this.type,t),e.shaderLanguage===1&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.declarationVariableName,this.type,t):this._emit(e._vertexState,t);return}if(e.attributes.indexOf(this.declarationVariableName)!==-1)return;e.attributes.push(this.declarationVariableName),Gne[this.name]?iMe[this.name]?(e._emitUniformFromString(this.declarationVariableName,this.type,t),e.shaderLanguage===1&&(this._prefix="uniforms.")):(e._emitVaryingFromString(this.declarationVariableName,this.type,t),e.shaderLanguage===1&&(this._prefix="fragmentInputs.")):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===1?(e._attributeDeclaration+=`attribute ${this.declarationVariableName}: ${e._getShaderType(this.type)}; `,this._prefix="vertexInputs."):e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.declarationVariableName}; `,t&&(e._attributeDeclaration+=`#endif `))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;const n=this._associatedVariableName;switch(this._systemValue){case mr.World:e.setMatrix(n,t);break;case mr.WorldView:e.setMatrix(n,i);break;case mr.WorldViewProjection:e.setMatrix(n,r);break}}_transmit(e,t,i){if(this.isAttribute)return;const r=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case mr.World:case mr.WorldView:case mr.WorldViewProjection:return;case mr.View:e.setMatrix(r,t.getViewMatrix());break;case mr.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case mr.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case mr.CameraPosition:t.bindEyePosition(e,r,!0);break;case mr.FogColor:e.setColor3(r,t.fogColor);break;case mr.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case mr.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case mr.MaterialAlpha:e.setFloat(r,i.alpha);break}return}const n=this._valueCallback?this._valueCallback():this._storedValue;if(n!==null)switch(this.type){case ee.Float:e.setFloat(r,n);break;case ee.Int:e.setInt(r,n);break;case ee.Color3:ts.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&ts.Color3[0].toGammaSpaceToRef(ts.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ts.Color3[0].toLinearSpaceToRef(ts.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,ts.Color3[0]);break;case ee.Color4:ts.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&ts.Color4[0].toGammaSpaceToRef(ts.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ts.Color4[0].toLinearSpaceToRef(ts.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,ts.Color4[0]);break;case ee.Vector2:e.setVector2(r,n);break;case ee.Vector3:e.setVector3(r,n);break;case ee.Vector4:e.setVector4(r,n);break;case ee.Matrix:e.setMatrix(r,n);break}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); `;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${mr[this._systemValue]}); `;if(this.isUniform){const t=[];let i="";switch(this.type){case ee.Float:i=`${this.value}`;break;case ee.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case ee.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case ee.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case ee.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ee.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ee.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===ee.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${w1[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(`; `)}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this._storedValue!=null&&this._mode===0&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.name==="tangent"&&e.mode===1&&e.type===ee.Vector3&&(this._type=ee.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const r=Xn(e.valueType);r&&(this._storedValue=r.FromArray(e.value))}}}ve("BABYLON.InputBlock",nr);class O1e extends qt{constructor(e){super(e,be.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ee.AutoDetect,!1,be.VertexAndFragment),this.registerOutput("rgba",ee.Color4,be.Neutral),this.registerOutput("rgb",ee.Color3,be.Neutral),this.registerOutput("r",ee.Float,be.Neutral),this.registerOutput("g",ee.Float,be.Neutral),this.registerOutput("b",ee.Float,be.Neutral),this.registerOutput("a",ee.Float,be.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector2|ee.Vector3|ee.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName(this._samplerName)}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?be.VertexAndFragment:be.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,ee.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,ee.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; `,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===be.Fragment)return;const n=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,a=e.shaderLanguage===0?"":", 0";e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${n} ${i.associatedVariableName}${a}); `;return}const r=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;if(this.uv.ownerBlock.target===be.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${r} ${i.associatedVariableName}); `;return}e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${r} ${this._mainUVName}); `}_writeOutput(e,t,i,r=!1){if(r){if(e.target===be.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===be.Fragment){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `;return}e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `,e.compilationString+=`#ifdef ${this._linearDefineName} `,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `,e.compilationString+=`#ifdef ${this._gammaDefineName} `,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==be.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(i=>i.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=xe.Parse(e.texture,t,i))}}ve("BABYLON.CurrentScreenBlock",O1e);class N1e extends qt{constructor(e){super(e,be.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ee.AutoDetect,!1,be.VertexAndFragment),this.registerOutput("rgba",ee.Color4,be.Neutral),this.registerOutput("rgb",ee.Color3,be.Neutral),this.registerOutput("r",ee.Float,be.Neutral),this.registerOutput("g",ee.Float,be.Neutral),this.registerOutput("b",ee.Float,be.Neutral),this.registerOutput("a",ee.Float,be.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector2|ee.Vector3|ee.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="particle_uv"&&t(r));i||(i=new nr("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `,e.compilationString+=`#ifdef ${this._linearDefineName} `,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `,e.compilationString+=`#ifdef ${this._gammaDefineName} `,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `}_buildBlock(e){if(super._buildBlock(e),e.target===be.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${e._generateTextureSample(this.uv.associatedVariableName,this._samplerName)}; `;for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=xe.Parse(e.texture,t,i))}}ve("BABYLON.ParticleTextureBlock",N1e);class F1e extends qt{constructor(e){super(e,be.Fragment),this._isUnique=!0,this.registerInput("color",ee.Color4,!1,be.Fragment),this.registerOutput("rampColor",ee.Color4,be.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor")}_buildBlock(e){if(super._buildBlock(e),e.target!==be.Vertex)return e._emit2DSampler("rampSampler","RAMPGRADIENT"),e._emitVaryingFromString("remapRanges",ee.Vector4,"RAMPGRADIENT"),e.compilationString+=` #ifdef RAMPGRADIENT ${e._declareLocalVar("baseColor",ee.Vector4)} = ${this.color.associatedVariableName}; ${e._declareLocalVar("alpha",ee.Float)} = ${this.color.associatedVariableName}.a; ${e._declareLocalVar("remappedColorIndex",ee.Float)} = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); ${e._declareLocalVar("rampColor",ee.Vector4)} = ${e._generateTextureSample("vec2(1.0 - remappedColorIndex, 0.)","rampSampler")}; // Remapped alpha ${e._declareOutput(this.rampColor)} = vec4${e.fSuffix}(baseColor.rgb * rampColor.rgb, clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0)); #else ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName}; #endif `,this}}ve("BABYLON.ParticleRampGradientBlock",F1e);class B1e extends qt{constructor(e){super(e,be.Fragment),this._isUnique=!0,this.registerInput("color",ee.Color4,!1,be.Fragment),this.registerInput("alphaTexture",ee.Float,!1,be.Fragment),this.registerInput("alphaColor",ee.Float,!1,be.Fragment),this.registerOutput("blendColor",ee.Color4,be.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==be.Vertex)return e.compilationString+=` #ifdef BLENDMULTIPLYMODE ${e._declareOutput(this.blendColor)}; ${e._declareLocalVar("sourceAlpha",ee.Float)} = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; ${this.blendColor.associatedVariableName} = vec4${e.fSuffix}(${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha), ${this.color.associatedVariableName}.a); #else ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName}; #endif `,this}}ve("BABYLON.ParticleBlendMultiplyBlock",B1e);class jB extends qt{constructor(e){super(e,be.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",ee.Vector4,!0),this.registerInput("xyz ",ee.Vector3,!0),this.registerInput("xy ",ee.Vector2,!0),this.registerInput("zw ",ee.Vector2,!0),this.registerInput("x",ee.Float,!0),this.registerInput("y",ee.Float,!0),this.registerInput("z",ee.Float,!0),this.registerInput("w",ee.Float,!0),this.registerOutput("xyzw",ee.Vector4),this.registerOutput("xyz",ee.Vector3),this.registerOutput("xy",ee.Vector2),this.registerOutput("zw",ee.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,r=this.z,n=this.w,a=this.xyIn,o=this.zwIn,l=this.xyzIn,c=this.xyzwIn,u=this._outputs[0],h=this._outputs[1],d=this._outputs[2],f=this._outputs[3],p=e._getShaderType(ee.Vector4),m=e._getShaderType(ee.Vector3),g=e._getShaderType(ee.Vector2);return c.isConnected?(u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${c.associatedVariableName}${this._buildSwizzle(4)}; `),h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${c.associatedVariableName}${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${c.associatedVariableName}${this._buildSwizzle(2)}; `)):l.isConnected?(u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${p}(${l.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(4)}; `),h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; `)):a.isConnected?(u.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(u)+` = ${p}(${a.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)}; `:e.compilationString+=e._declareOutput(u)+` = ${p}(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(4)}; `),h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${m}(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; `),f.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(f)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; `:e.compilationString+=e._declareOutput(f)+` = ${g}(${r.isConnected?this._writeVariable(r):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(2)}; `)):(u.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(u)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)}; `:e.compilationString+=e._declareOutput(u)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(4)}; `),h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${m}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${g}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; `),f.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(f)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; `:e.compilationString+=e._declareOutput(f)+` = ${g}(${r.isConnected?this._writeVariable(r):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(2)}; `)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; `,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; `,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; `,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; `,e}}ve("BABYLON.VectorMergerBlock",jB);class jz extends qt{constructor(e){super(e,be.Neutral),this.sourceRange=new we(-1,1),this.targetRange=new we(0,1),this.registerInput("input",ee.AutoDetect),this.registerInput("sourceMin",ee.Float,!0),this.registerInput("sourceMax",ee.Float,!0),this.registerInput("targetMin",ee.Float,!0),this.registerInput("targetMax",ee.Float,!0),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),n=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),a=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=e._declareOutput(t)+` = ${n} + (${this._inputs[0].associatedVariableName} - ${i}) * (${a} - ${n}) / (${r} - ${i}); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); `;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); `,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=we.FromArray(e.sourceRange),this.targetRange=we.FromArray(e.targetRange)}}F([Jt("From",3)],jz.prototype,"sourceRange",void 0);F([Jt("To",3)],jz.prototype,"targetRange",void 0);ve("BABYLON.RemapBlock",jz);class mee extends qt{constructor(e){super(e,be.Neutral),this.registerInput("left",ee.AutoDetect),this.registerInput("right",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(ee.Float),this.right.acceptedConnectionPointTypes.push(ee.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add(()=>this._updateInputOutputTypes()),this.right.onTypeChangedObservable.add(()=>this._updateInputOutputTypes())]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===ee.Int||this.left.type===ee.Float&&this.right.type!==ee.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[ee.Int,ee.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),(t.type===ee.Int||t.type===ee.Float)&&e.acceptedConnectionPointTypes.push(ee.Vector2,ee.Vector3,ee.Vector4,ee.Color3,ee.Color4,ee.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach(e=>e.remove()),this._connectionObservers.length=0}}class yZ extends mee{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; `,this}}ve("BABYLON.MultiplyBlock",yZ);var Eu;(function(s){s[s.Material=0]="Material",s[s.PostProcess=1]="PostProcess",s[s.Particle=2]="Particle",s[s.ProceduralTexture=3]="ProceduralTexture"})(Eu||(Eu={}));class gyt extends _s{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class zo{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:D.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:D.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:D.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:D.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(const n of t){if(n.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=D.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new D(10,10,10),this.onAnimationEnd=null,this.blendMode=zo.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new we(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new D(0,0,0),this._useLogarithmicDepth=!1,this.gravity=D.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Ze(1,1,1,1),this.color2=new Ze(1,1,1,1),this.colorDead=new Ze(0,0,0,1),this.textureMask=new Ze(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new gyt,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new D(0,1,0),i=new D(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,r=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new D(0,1,0),n=new D(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new D(0,1,0),r=new D(0,1,0)){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,r){throw new Error("Method not implemented.")}}zo.BLENDMODE_ONEONE=0;zo.BLENDMODE_STANDARD=1;zo.BLENDMODE_ADD=2;zo.BLENDMODE_MULTIPLY=3;zo.BLENDMODE_MULTIPLYADD=4;ve("BABYLON.BaseParticleSystem",zo);class k1e extends qt{constructor(e){super(e,be.Neutral),this.registerInput("rgba",ee.Color4,!0),this.registerInput("rgb ",ee.Color3,!0),this.registerOutput("rgb",ee.Color3),this.registerOutput("r",ee.Float),this.registerOutput("g",ee.Float),this.registerOutput("b",ee.Float),this.registerOutput("a",ee.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return e==="rgb "?"rgbIn":e}_outputRename(e){return e==="rgb"?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],r=this._outputs[1],n=this._outputs[2],a=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb; `),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.r; `),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.g; `),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = ${t.associatedVariableName}.b; `),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a; `),this}}ve("BABYLON.ColorSplitterBlock",k1e);class gUe{constructor(e){this.name=ot.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(ot.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Me.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const _yt="proceduralVertexShader",vyt=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[_yt]=vyt;class O0 extends xe{constructor(e,t,i,r,n=null,a=!0,o=!1,l=0){super(null,r,!a),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new Ae,this.onBeforeGenerationObservable=new Ae,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,n!==null&&!(n instanceof xe)?(this._options=n,this._fallbackTexture=n.fallbackTexture??null):(this._options={},this._fallbackTexture=n),r=this.getScene()||Rt.LastCreatedScene;let c=r._getComponent(ot.NAME_PROCEDURALTEXTURE);c||(c=new gUe(r),r._addComponent(c)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=a,this._drawWrapper=new Ro(this._fullEngine),this.setFragment(i);const u=this._createRtWrapper(o,t,a,l);this._texture=u.texture;const h=[];h.push(1,1),h.push(-1,1),h.push(-1,-1),h.push(1,-1),this._vertexBuffers[$.PositionKind]=new $(this._fullEngine,h,$.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId?this._contentData:(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId),this._contentData)}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[$.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Rs.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Rs.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)==null||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady()){e(this);return}const t=this.getEffect();t&&t.executeWhenCompiled(()=>{e(this)})}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:typeof this._fragment=="string"?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[$.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var r;(r=this._rtWrapper)==null||r.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return!this.isEnabled||!this.isReady()||!this._texture?(this._texture&&(this._texture.isReady=!1),!1):this._fallbackTextureUsed?!1:this._currentRefreshId===-1?(this._currentRefreshId=1,this._frameId++,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)}setTexture(e,t){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var n,a,o;const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const l in this._textures)this._drawWrapper.effect.setTexture(l,this._textures[l]);for(const l in this._ints)this._drawWrapper.effect.setInt(l,this._ints[l]);for(const l in this._floats)this._drawWrapper.effect.setFloat(l,this._floats[l]);for(const l in this._floatsArrays)this._drawWrapper.effect.setArray(l,this._floatsArrays[l]);for(const l in this._colors3)this._drawWrapper.effect.setColor3(l,this._colors3[l]);for(const l in this._colors4){const c=this._colors4[l];this._drawWrapper.effect.setFloat4(l,c.r,c.g,c.b,c.a)}for(const l in this._vectors2)this._drawWrapper.effect.setVector2(l,this._vectors2[l]);for(const l in this._vectors3)this._drawWrapper.effect.setVector3(l,this._vectors3[l]);for(const l in this._vectors4)this._drawWrapper.effect.setVector4(l,this._vectors4[l]);for(const l in this._matrices)this._drawWrapper.effect.setMatrix(l,this._matrices[l])}if(!this._texture||!this._rtWrapper)return;(n=i._debugPushGroup)==null||n.call(i,`procedural texture generation for ${this.name}`,1);const r=i.currentViewport;if(this.isCube)for(let l=0;l<6;l++)i.bindFramebuffer(this._rtWrapper,l,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",l),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Ye.TriangleFillMode,0,6);else{let l=1;this._rtWrapper.is3D?l=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(l=this._rtWrapper.layers);for(let c=0;c=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[$.PositionKind];i&&(i.dispose(),this._vertexBuffers[$.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}F([X()],O0.prototype,"isEnabled",void 0);F([X()],O0.prototype,"autoClear",void 0);F([X()],O0.prototype,"_generateMipMaps",void 0);F([X()],O0.prototype,"_size",void 0);F([X()],O0.prototype,"refreshRate",null);ve("BABYLON.ProceduralTexture",O0);var xo;(function(s){s[s.Cos=0]="Cos",s[s.Sin=1]="Sin",s[s.Abs=2]="Abs",s[s.Exp=3]="Exp",s[s.Exp2=4]="Exp2",s[s.Round=5]="Round",s[s.Floor=6]="Floor",s[s.Ceiling=7]="Ceiling",s[s.Sqrt=8]="Sqrt",s[s.Log=9]="Log",s[s.Tan=10]="Tan",s[s.ArcTan=11]="ArcTan",s[s.ArcCos=12]="ArcCos",s[s.ArcSin=13]="ArcSin",s[s.Fract=14]="Fract",s[s.Sign=15]="Sign",s[s.Radians=16]="Radians",s[s.Degrees=17]="Degrees",s[s.Set=18]="Set"})(xo||(xo={}));class U1e extends qt{constructor(e){super(e,be.Neutral),this.operation=xo.Cos,this.registerInput("input",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case xo.Cos:{i="cos";break}case xo.Sin:{i="sin";break}case xo.Abs:{i="abs";break}case xo.Exp:{i="exp";break}case xo.Exp2:{i="exp2";break}case xo.Round:{i="round";break}case xo.Floor:{i="floor";break}case xo.Ceiling:{i="ceil";break}case xo.Sqrt:{i="sqrt";break}case xo.Log:{i="log";break}case xo.Tan:{i="tan";break}case xo.ArcTan:{i="atan";break}case xo.ArcCos:{i="acos";break}case xo.ArcSin:{i="asin";break}case xo.Fract:{i="fract";break}case xo.Sign:{i="sign";break}case xo.Radians:{i="radians";break}case xo.Degrees:{i="degrees";break}case xo.Set:{i="";break}}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName}); `,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${xo[this.operation]}; `}}ve("BABYLON.TrigonometryBlock",U1e);const Wne={effect:null,subMesh:null};class _B extends _s{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){this[e]===void 0&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Ss extends aa{static _BlockIsTextureBlock(e){return e.getClassName()==="TextureBlock"||e.getClassName()==="ReflectionTextureBaseBlock"||e.getClassName()==="ReflectionTextureBlock"||e.getClassName()==="ReflectionBlock"||e.getClassName()==="RefractionBlock"||e.getClassName()==="CurrentScreenBlock"||e.getClassName()==="ParticleTextureBlock"||e.getClassName()==="ImageSourceBlock"||e.getClassName()==="TriPlanarBlock"||e.getClassName()==="BiPlanarBlock"||e.getClassName()==="PrePassTextureBlock"}_getGlobalNodeMaterialEditor(){if(typeof NODEEDITOR<"u")return NODEEDITOR;if(typeof BABYLON<"u"&&typeof BABYLON.NodeEditor<"u")return BABYLON}get shaderLanguage(){return this._options.shaderLanguage}set shaderLanguage(e){this._options.shaderLanguage=e}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||Rt.LastCreatedScene),this._buildId=Ss._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new he,this._cachedWorldViewProjectionMatrix=new he,this._optimizers=new Array,this._animationFrame=-1,this._buildIsInProgress=!1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new Ae,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=Eu.Material,this.forceAlphaBlending=!1,i&&i.shaderLanguage===1&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:Ss.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return Me.Warn("More than one block was found with the name `"+e+"`"),t;return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(t!==-1)return this._optimizers.splice(t,1),this}addOutputNode(e){if(e.target===null)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&be.Vertex&&this._addVertexOutputNode(e),e.target&be.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&be.Vertex&&this._removeVertexOutputNode(e),e.target&be.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=be.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(t!==-1)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(this._fragmentOutputNodes.indexOf(e)===-1)return e.target=be.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(t!==-1)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return this.ignoreAlpha?!1:this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){(e.target===be.VertexAndFragment||t.target===be.Fragment&&e.target===be.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){const n=e.getClassName();for(const a of this.attachedBlocks)if(a.getClassName()===n)throw`Cannot have multiple blocks of type ${n} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const n of e.inputs){n.associatedVariableName="";const a=n.connectedPoint;if(a){const o=a.ownerBlock;o!==e&&this._processInitializeOnLink(o,t,i,r)}}if(e.isTeleportOut){const n=e;n.entryPoint&&this._processInitializeOnLink(n.entryPoint,t,i,r)}for(const n of e.outputs)n.associatedVariableName=""}_resetDualBlocks(e,t){e.target===be.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const r=i.connectedPoint;if(r){const n=r.ownerBlock;n!==e&&this._resetDualBlocks(n,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){if(this._buildIsInProgress){fe.Warn("Build is already in progress, You can use NodeMaterial.onBuildObservable to determine when the build is completed.");return}this._buildIsInProgress=!0,!this._vertexCompilationState&&!i&&(i=!0),this._buildWasSuccessful=!1;const r=this.getScene().getEngine(),n=this._mode===Eu.Particle;if(this._vertexOutputNodes.length===0&&!n)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new tMe,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=be.Vertex,this._fragmentCompilationState=new tMe,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=be.Fragment,this._sharedData=new pyt,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=n;const a=[],o=[];for(const c of this._vertexOutputNodes)a.push(c),this._initializeBlock(c,this._vertexCompilationState,o,i);for(const c of this._fragmentOutputNodes)o.push(c),this._initializeBlock(c,this._fragmentCompilationState,a,i);let l=0;for(const c of this.attachedBlocks)c.codeIsReady||(l++,c.onCodeIsReadyObservable.addOnce(()=>{l--,l===0&&this._finishBuildProcess(e,t,a,o)}));l===0&&this._finishBuildProcess(e,t,a,o)}_finishBuildProcess(e=!1,t=!0,i,r){this.optimize();for(const o of i)o.build(this._vertexCompilationState,i);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const o of r)this._resetDualBlocks(o,this._buildId-1);for(const o of r)o.build(this._fragmentCompilationState,r);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Ss._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(fe.Log("Vertex shader:"),fe.Log(this._vertexCompilationState.compilationString),fe.Log("Fragment shader:"),fe.Log(this._fragmentCompilationState.compilationString)),this._buildIsInProgress=!1,this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const n=this.getScene().meshes;for(const o of n)if(o.subMeshes)for(const l of o.subMeshes){if(l.getMaterial()!==this||!l.materialDefines)continue;const c=l.materialDefines;c.markAllAsDirty(),c.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const a=this.getScene().prePassRenderer;a&&a.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,r=t.TANGENT,n=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent($.NormalKind),t.TANGENT=e.isVerticesDataPresent($.TangentKind);const a=e.useVertexColors&&e.isVerticesDataPresent($.ColorKind);t.VERTEXCOLOR_NME=a;let o=!1;for(let c=1;c<=6;++c){const u=t["UV"+c];t["UV"+c]=e.isVerticesDataPresent(`uv${c===1?"":c}`),o=o||t["UV"+c]!==u}const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;mz(this.getScene(),t,!l),(i!==t.NORMAL||r!==t.TANGENT||n!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate(i=>i.getClassName()==="PrePassOutputBlock"),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter(i=>i.getClassName()==="PrePassTextureBlock"),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const r of t)i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,n,a=0,o=5){return this.mode!==Eu.PostProcess?(fe.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,n,a,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,n,a,o=0,l=5){let c=this.name+this._buildId;const u=new _B,h=new Ee(c+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(h,u),zi.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),e?e.updateEffect(u.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,c,c):e=new Ft(this.name+"PostProcess",c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,n,a,u.toString(),o,c,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l,this.shaderLanguage),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete zi.ShadersStore[c+"VertexShader"],delete zi.ShadersStore[c+"PixelShader"],c=this.name+this._buildId,u.markAllAsDirty(),d=this._buildId),this._processDefines(h,u)&&(zi.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),ew.SetImmediate(()=>e.updateEffect(u.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,c,c))),this._checkInternals(f)}),e}createProceduralTexture(e,t){if(this.mode!==Eu.ProceduralTexture)return fe.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const r=new O0(i,e,null,t),n=new Ee(i+"Procedural",this.getScene());n.reservedDataStore={hidden:!0};const a=new _B,o=this._processDefines(n,a);zi.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[$.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),o==null?void 0:o.fallbacks,void 0,void 0,void 0,this.shaderLanguage);r.nodeMaterialSource=this,r._setEffect(l);let c=this._buildId;const u=()=>{c!==this._buildId&&(delete zi.ShadersStore[i+"VertexShader"],delete zi.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,a.markAllAsDirty(),c=this._buildId);const h=this._processDefines(n,a);h&&(zi.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),ew.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[$.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),h==null?void 0:h.fallbacks,void 0),r._setEffect(l)})),this._checkInternals(l)};return r.onBeforeGenerationObservable.add(()=>{u()}),this.onBuildObservable.add(()=>{u()}),r}_createEffectForParticles(e,t,i,r,n,a,o,l=""){let c=this.name+this._buildId+"_"+t;a||(a=new _B),o||(o=this.getScene().getMeshByName(this.name+"Particle"),o||(o=new Ee(this.name+"Particle",this.getScene()),o.reservedDataStore={hidden:!0}));let u=this._buildId;const h=[];let d=l;if(!n){const f=this._processDefines(o,a);zi.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),e.fillDefines(h,t,!1),d=h.join(` `),n=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+` `+d,f==null?void 0:f.fallbacks,i,r,e,this.shaderLanguage),e.setCustomEffect(n,t)}n.onBindObservable.add(f=>{u!==this._buildId&&(delete zi.ShadersStore[c+"PixelShader"],c=this.name+this._buildId+"_"+t,a.markAllAsDirty(),u=this._buildId),h.length=0,e.fillDefines(h,t,!1);const p=h.join(` `);p!==d&&(a.markAllAsDirty(),d=p);const m=this._processDefines(o,a);if(m){zi.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),f=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+` `+d,m==null?void 0:m.fallbacks,i,r,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,r,f,a,o,l);return}this._checkInternals(f)})}_checkInternals(e){if(this._sharedData.animatedInputs){const t=this.getScene(),i=t.getFrameId();if(this._animationFrame!==i){for(const r of this._sharedData.animatedInputs)r.animate(t);this._animationFrame=i}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==Eu.Particle){fe.Log("Incompatible material mode");return}this._createEffectForParticles(e,zo.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,zo.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==Eu.Material){fe.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let n=null;const a=this.getScene();if(NJ(a,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(o=>{o.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(o=>{o.prepareDefines(e,this,t,i,r)}),t.isDirty){const o=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(d=>{d.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});const l=[];this._sharedData.dynamicUniformBlocks.forEach(d=>{d.updateUniformsAndSamples(this._vertexCompilationState,this,t,l)});const c=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(d=>{c.indexOf(d)===-1&&c.push(d)});const u=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(d=>{u.indexOf(d)===-1&&u.push(d)});const h=new oa;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,h)}),n={lightDisposed:o,uniformBuffers:l,mergedUniforms:c,mergedSamplers:u,fallbacks:h}}return n}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const r=this.getScene();if(this._sharedData.animatedInputs){const c=r.getFrameId();if(this._animationFrame!==c){for(const u of this._sharedData.animatedInputs)u.animate(r);this._animationFrame=c}}const n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new _B);const a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(this._prepareDefinesForAttributes(e,a),this._sharedData.blockingBlocks.some(c=>!c.isReady(e,this,a,i)))return!1;const l=this._processDefines(e,a,i,t);if(l){const c=t.effect,u=a.toString();let h=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:l.mergedUniforms,uniformBuffersNames:l.uniformBuffers,samplers:l.mergedSamplers,defines:u,fallbacks:l.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:a.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(h)if(this._onEffectCreatedObservable&&(Wne.effect=h,Wne.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Wne)),this.allowShaderHotSwapping&&c&&!h.isReady()){if(h=c,a.markAsUnprocessed(),l.lightDisposed)return a._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(h,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=r.getRenderId(),n._wasPreviouslyReady=!0,n._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader ${this._vertexCompilationState.compilationString} // Fragment shader ${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const r of this._sharedData.inputBlocks)r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const r=this.getScene(),n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e);const a=this._mustRebind(r,n,i,t.visibility),o=this._sharedData;if(a){for(const l of o.bindableBlocks)l.bind(n,this,t,i);for(const l of o.forcedBindableBlocks)l.bind(n,this,t,i);for(const l of o.inputBlocks)l._transmit(n,r,this)}else if(!this.isFrozen)for(const l of o.forcedBindableBlocks)l.bind(n,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(t=>t.texture).map(t=>t.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Ss._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const r of this.getTextureBlocks().filter(n=>n.texture).map(n=>n.texture))r.dispose();for(const r of this.attachedBlocks)r.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),typeof this.BJSNODEMATERIALEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:Ss.EditorURL;Me.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e==null?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(e==null?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new nr("Position");e.setAsAttribute("position");const t=new nr("World");t.setAsSystemValue(mr.World);const i=new vZ("WorldPos");e.connectTo(i),t.connectTo(i);const r=new nr("ViewProjection");r.setAsSystemValue(mr.ViewProjection);const n=new vZ("WorldPos * ViewProjectionTransform");i.connectTo(n),r.connectTo(n);const a=new HB("VertexOutput");n.connectTo(a);const o=new nr("color");o.value=new Ze(.8,.8,.8,1);const l=new dv("FragmentOutput");o.connectTo(l),this.addOutputNode(a),this.addOutputNode(l),this._mode=Eu.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new nr("Position");e.setAsAttribute("position2d");const t=new nr("Constant1");t.isConstant=!0,t.value=1;const i=new jB("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new HB("VertexOutput");i.connectTo(r);const n=new nr("Scale");n.visibleInInspector=!0,n.value=new we(1,1);const a=new jz("uv0");e.connectTo(a);const o=new yZ("UV scale");a.connectTo(o),n.connectTo(o);const l=new O1e("CurrentScreen");o.connectTo(l),l.texture=new xe("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const c=new dv("FragmentOutput");l.connectTo(c,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(c),this._mode=Eu.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new nr("Position");e.setAsAttribute("position2d");const t=new nr("Constant1");t.isConstant=!0,t.value=1;const i=new jB("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new HB("VertexOutput");i.connectTo(r);const n=new nr("Time");n.value=0,n.min=0,n.max=0,n.isBoolean=!1,n.matrixMode=0,n.animationType=w1.Time,n.isConstant=!1;const a=new nr("Color3");a.value=new Re(1,1,1),a.isConstant=!1;const o=new dv("FragmentOutput"),l=new jB("VectorMerger");l.visibleInInspector=!1;const c=new U1e("Cos");c.operation=xo.Cos,e.connectTo(l),n.output.connectTo(c.input),c.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(r),this.addOutputNode(o),this._mode=Eu.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new nr("uv");e.setAsAttribute("particle_uv");const t=new N1e("ParticleTexture");e.connectTo(t);const i=new nr("Color");i.setAsAttribute("particle_color");const r=new yZ("Texture * Color");t.connectTo(r),i.connectTo(r);const n=new F1e("ParticleRampGradient");r.connectTo(n);const a=new k1e("ColorSplitter");i.connectTo(a);const o=new B1e("ParticleBlendMultiply");n.connectTo(o),t.connectTo(o,{output:"a"}),a.connectTo(o,{output:"a"});const l=new dv("FragmentOutput");o.connectTo(l),this.addOutputNode(l),this._mode=Eu.Particle}async loadAsync(e,t=""){return Ss.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const n=r.ownerBlock;n!==e&&this._gatherBlocks(n,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const a of this._vertexOutputNodes)this._gatherBlocks(a,t);const r=[];for(const a of this._fragmentOutputNodes)this._gatherBlocks(a,r);let n=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); `;n+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${Eu[this.mode]}; `;for(const a of t)a.isInput&&e.indexOf(a)===-1&&(n+=a._dumpCode(i,e));for(const a of r)a.isInput&&e.indexOf(a)===-1&&(n+=a._dumpCode(i,e));e=[],n+=` // Connections `;for(const a of this._vertexOutputNodes)n+=a._dumpCodeForOutputConnections(e);for(const a of this._fragmentOutputNodes)n+=a._dumpCodeForOutputConnections(e);n+=` // Output nodes `;for(const a of this._vertexOutputNodes)n+=`nodeMaterial.addOutputNode(${a._codeVariableName}); `;for(const a of this._fragmentOutputNodes)n+=`nodeMaterial.addOutputNode(${a._codeVariableName}); `;return n+=`nodeMaterial.build(); `,n}serialize(e){const t=e?{}:qe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const r of this._vertexOutputNodes)this._gatherBlocks(r,i),t.outputNodes.push(r.uniqueId);for(const r of this._fragmentOutputNodes)this._gatherBlocks(r,i),t.outputNodes.indexOf(r.uniqueId)===-1&&t.outputNodes.push(r.uniqueId)}t.blocks=[];for(const r of i)t.blocks.push(r.serialize());if(!e)for(const r of this.attachedBlocks)i.indexOf(r)===-1&&t.blocks.push(r.serialize());return t.uniqueId=this.uniqueId,t}_restoreConnections(e,t,i){for(const r of e.outputs)for(const n of t.blocks){const a=i[n.id];if(a){for(const o of n.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===r.name){const l=a.getInputByName(o.inputName);if(!l||l.isConnected)continue;r.connectTo(l,!0),this._restoreConnections(a,t,i);continue}}}}parseSerializedObject(e,t="",i=!1,r){i||this.clear();const n={};for(const a of e.blocks){const o=Xn(a.customType);if(o){const l=new o;l._deserialize(a,this.getScene(),t,r),n[a.id]=l,this.attachedBlocks.push(l)}}for(const a of this.attachedBlocks)if(a.isTeleportOut){const o=a,l=o._tempEntryPointUniqueId;l&&n[l].attachToEndpoint(o)}for(let a=0;anew Ss(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach(t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((r,n)=>{i.onLoadedObservable.addOnce(()=>{r()}),i.onErrorObservable.addOnce(a=>{n(a)})}))}),Promise.all(e)}static Parse(e,t,i="",r=0){const n=qe.Parse(()=>new Ss(e.name,t,{shaderLanguage:r}),e,t,i);return n.parseSerializedObject(e,i),n.build(),n}static async ParseFromFileAsync(e,t,i,r="",n=!1,a,o){const l=a??new Ss(e,i),c=await i._loadFileAsync(t),u=JSON.parse(c);return l.parseSerializedObject(u,r,void 0,o),n||l.build(),l}static ParseFromSnippetAsync(e,t=Rt.LastCreatedScene,i="",r,n=!1,a=!1,o){return e==="_BLANK"?Promise.resolve(Ss.CreateDefault("blank",t)):new Promise((l,c)=>{const u=new On;u.addEventListener("readystatechange",()=>{if(u.readyState==4)if(u.status==200){const h=JSON.parse(JSON.parse(u.responseText).jsonPayload),d=JSON.parse(h.nodeMaterial);r||(r=qe.Parse(()=>new Ss(e,t),d,t,i),r.uniqueId=t.getUniqueId()),r.parseSerializedObject(d,void 0,void 0,o),r.snippetId=e,r.sideOrientation=null;try{n||r.build()}catch(f){c(f)}a?r.whenTexturesReadyAsync().then(()=>{l(r)}).catch(f=>{c(f)}):l(r)}else c("Unable to load the snippet "+e)}),u.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),u.send()})}static CreateDefault(e,t){const i=new Ss(e,t);return i.setToDefault(),i.build(),i}}Ss._BuildIdGenerator=0;Ss.EditorURL=`${Me._DefaultCdnUrl}/v${Ge.Version}/nodeEditor/babylon.nodeEditor.js`;Ss.SnippetUrl="https://snippet.babylonjs.com";Ss.IgnoreTexturesAtLoadTime=!1;Ss.DefaultShaderLanguage=0;F([X()],Ss.prototype,"ignoreAlpha",void 0);F([X()],Ss.prototype,"maxSimultaneousLights",void 0);F([X("mode")],Ss.prototype,"_mode",void 0);F([X("comment")],Ss.prototype,"comment",void 0);F([X()],Ss.prototype,"forceAlphaBlending",void 0);ve("BABYLON.NodeMaterial",Ss);wl.prototype._projectOnTrianglesToRef=function(s,e,t,i,r,n){const a=se.Vector3[0],o=se.Vector3[1];let l=1/0;for(let c=this.indexStart;c{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:r,touchCollisionMeshFunction:n,hydrateCollisionMeshFunction:a}=this._generateNewTouchPointMesh(),o=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:r,touchCollisionMeshFunction:n,hydrateCollisionMeshFunction:a,currentAnimationState:Rd.DEHYDRATED,grabRay:new $i(new D,new D),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:tg._IdCounter++,pickedPointVisualCue:o},this._controllers[i.uniqueId]._worldScaleObserver=this._controllers[i.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add(l=>{if(l.newScaleFactor!==l.previousScaleFactor){this._controllers[i.uniqueId].touchCollisionMesh.dispose(),this._controllers[i.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:c,touchCollisionMeshFunction:u,hydrateCollisionMeshFunction:h}=this._generateNewTouchPointMesh();this._controllers[i.uniqueId].touchCollisionMesh=c,this._controllers[i.uniqueId].touchCollisionMeshFunction=u,this._controllers[i.uniqueId].hydrateCollisionMeshFunction=h,this._controllers[i.uniqueId].pickedPointVisualCue=this._generateVisualCue()}}),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(i);case"gaze":return null;case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Re(.8,.8,.8),this.selectionMeshPickedColor=new Re(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,this._options.nearInteractionControllerMode===void 0&&(this._options.nearInteractionControllerMode=2),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return super.attach()?(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0):!1}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case Rd.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Rd.HOVER)break;case Rd.HOVER:if(e.touchCollisionMeshFunction(!0),t===Rd.TOUCH)break}else switch(e.currentAnimationState){case Rd.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Rd.HOVER)break;case Rd.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Rd.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var n;const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(se.Vector3[0]),r.grabRay.direction.copyFrom(se.Vector3[0]),this._options.nearInteractionControllerMode===2&&!((n=r.xrController)!=null&&n.inputSource.hand)&&(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var l;const i=this._controllers[t],r=(l=i.xrController)==null?void 0:l.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!r&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad)){i.pick=null;return}if(i.hoverInteraction=!1,i.nearInteraction=!1,i.xrController){if(r){const c=r.get("index-finger-tip");if(c){const u=e.getJointPose(c,this._xrSessionManager.referenceSpace);if(u&&u.transform){const h=this._scene.useRightHandedSystem?1:-1;se.Vector3[0].set(u.transform.position.x,u.transform.position.y,u.transform.position.z*h),se.Quaternion[0].set(u.transform.orientation.x,u.transform.orientation.y,u.transform.orientation.z*h,u.transform.orientation.w*h),this._processTouchPoint(t,se.Vector3[0],se.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==0){let c=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===1&&(c=i.xrController.grip),this._processTouchPoint(t,c.position,c.rotationQuaternion)}}else return;const n=(c,u)=>{let h=null;return!u||!u.hit?h=c:!c||!c.hit||u.distance{let u=new Ko,h=!1;const d=c&&c.pickedPoint&&c.hit;return c!=null&&c.pickedPoint&&(h=c.pickedPoint.x===0&&c.pickedPoint.y===0&&c.pickedPoint.z===0),d&&!h&&(u=c),u};if(!i.grabInteraction){let c=null,u=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(u=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,f=>this._nearInteractionPredicate(f)));const h=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,f=>this._nearInteractionPredicate(f)),d=n(h,u);if(d&&d.hit&&(c=a(d),c.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let f=null;const p=(r?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(i,p,this._utilityLayerScene,y=>this._nearPickPredicate(y)));const m=this._pickWithSphere(i,p,this._scene,y=>this._nearPickPredicate(y)),g=n(m,f),_=a(g);_.hit&&(c=_,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=c,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=Rd.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=Rd.TOUCH:i.hoverInteraction&&(o=Rd.HOVER),this._handleTransitionAnimation(i,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||is.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||is.DefaultUtilityLayer.utilityLayerScene:this._scene,t=kc("nearInteraction",{diameter:.0035*3*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=Pe.Identity();const i=new et("targetMat",e);return i.specularColor=Re.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return this._farInteractionFeature?this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e):!0}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{!this._options.enableNearInteractionOnAllControllers&&e.uniqueId!==this._attachedController||!t.xrController||!t.xrController.inputSource.hand&&(!this._options.nearInteractionControllerMode||!t.xrController.inputSource.gamepad)||(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))});const r=n=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),n&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!n&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):n&&!this._options.enableNearInteractionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const n=a=>{t.squeezeComponent=a.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;r(l)}}):(t.selectionComponent=a.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;r(l)}}))};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{const n=o=>{t.xrController&&o.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},a=o=>{t.xrController&&o.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:a,selectstart:n},this._xrSessionManager.session.addEventListener("selectstart",n),this._xrSessionManager.session.addEventListener("selectend",a)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(i=>{const r=t.eventListeners&&t.eventListeners[i];r&&this._xrSessionManager.session.removeEventListener(i,r)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{if(!t.downTriggered)return;const i={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new Ko,i)}),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const i=Object.keys(this._controllers);i.length?this._attachedController=i[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||is.DefaultUtilityLayer.utilityLayerScene:this._scene,i=kc("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let T;this._options.motionControllerTouchMaterialSnippetUrl?T=Ss.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):T=Ss.ParseFromSnippetAsync("8RUNKL#3",t),T.then(w=>{i.material=w}).catch(w=>{fe.Warn(`Error creating touch material in WebXRNearInteraction: ${w}`)})}const r=new xge;r.setEasingMode(ya.EASINGMODE_EASEINOUT);const n=new D(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),a=this._controllerPickRadius*(4/3),o=new D(a,a,a).scaleInPlace(e),l=this._controllerPickRadius*(7/6),c=new D(l,l,l).scaleInPlace(e),u=this._controllerPickRadius*(4/5),h=new D(u,u,u).scaleInPlace(e),d=this._controllerPickRadius*(3/2),f=new D(d,d,d).scaleInPlace(e),p=[{frame:0,value:n},{frame:10,value:f},{frame:18,value:o}],m=[{frame:0,value:o},{frame:10,value:h},{frame:18,value:n}],g=[{frame:0,value:D.ZeroReadOnly},{frame:12,value:c},{frame:15,value:n}],_=[{frame:0,value:n},{frame:10,value:D.ZeroReadOnly},{frame:15,value:D.ZeroReadOnly}],y=new tt("touch","scaling",60,tt.ANIMATIONTYPE_VECTOR3,tt.ANIMATIONLOOPMODE_CONSTANT),v=new tt("release","scaling",60,tt.ANIMATIONTYPE_VECTOR3,tt.ANIMATIONLOOPMODE_CONSTANT),x=new tt("hydrate","scaling",60,tt.ANIMATIONTYPE_VECTOR3,tt.ANIMATIONLOOPMODE_CONSTANT),A=new tt("dehydrate","scaling",60,tt.ANIMATIONTYPE_VECTOR3,tt.ANIMATIONLOOPMODE_CONSTANT);return y.setEasingFunction(r),v.setEasingFunction(r),x.setEasingFunction(r),A.setEasingFunction(r),y.setKeys(p),v.setKeys(m),x.setKeys(g),A.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:T=>{const w=T?y:v;t.beginDirectAnimation(i,[w],0,18,!1,1)},hydrateCollisionMeshFunction:T=>{const w=T?x:A;T&&(i.isVisible=!0),t.beginDirectAnimation(i,[w],0,15,!1,1,()=>{T||(i.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){const n=new Ko;if(n.distance=1/0,e.touchCollisionMesh&&e.xrController){const a=e.touchCollisionMesh.position,o=qm.CreateFromCenterAndRadius(a,t);for(let l=0;ld&&(h=0,l.copyFrom(t.center)),h!==-1&&h()=>new tg(s,e),tg.Version,!0);class _Ue{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class yyt{}class gee{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new Ae,this._onSessionGranted=r=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),typeof window<"u"&&window.location&&window.location.protocol==="http:"&&window.location.hostname!=="localhost")throw Me.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const r=t.sessionMode||"immersive-vr",n=t.referenceSpaceType||"local-floor";let o=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(typeof SVGSVGElement>"u"?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";o+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const l=document.createElement("style");l.appendChild(document.createTextNode(o)),document.getElementsByTagName("head")[0].appendChild(l);const c=document.createElement("button");c.className="babylonVRicon",c.title=`${r} - ${n}`,this._buttons.push(new _Ue(c,r,n)),this._buttons[this._buttons.length-1].update=function(u){this.element.style.display=u===null||u===this?"":"none",c.className="babylonVRicon"+(u===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map(n=>e.sessionManager.isSessionSupportedAsync(n.sessionMode));e.onStateChangedObservable.add(n=>{n==3&&this._updateButtons(null)}),(await Promise.all(i)).forEach((n,a)=>{n?(this.overlay.appendChild(this._buttons[a].element),this._buttons[a].element.onclick=this._enterXRWithButtonIndex.bind(this,a)):Me.Warn(`Session mode "${this._buttons[a].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const r=new gee(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==2)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==3)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,r=i.title;i.title="Error entering XR session : "+r,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(t=>{t.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}var Hhe;(function(s){s.WRIST="wrist",s.THUMB="thumb",s.INDEX="index",s.MIDDLE="middle",s.RING="ring",s.LITTLE="little"})(Hhe||(Hhe={}));var jhe;(function(s){s.WRIST="wrist",s.THUMB_METACARPAL="thumb-metacarpal",s.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",s.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",s.THUMB_TIP="thumb-tip",s.INDEX_FINGER_METACARPAL="index-finger-metacarpal",s.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",s.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",s.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",s.INDEX_FINGER_TIP="index-finger-tip",s.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",s.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",s.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",s.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",s.MIDDLE_FINGER_TIP="middle-finger-tip",s.RING_FINGER_METACARPAL="ring-finger-metacarpal",s.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",s.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",s.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",s.RING_FINGER_TIP="ring-finger-tip",s.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",s.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",s.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",s.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",s.PINKY_FINGER_TIP="pinky-finger-tip"})(jhe||(jhe={}));const Em=["wrist","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"],xyt={wrist:["wrist"],thumb:["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],index:["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],middle:["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],ring:["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],little:["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]};class vUe{get handMesh(){return this._handMesh}getHandPartMeshes(e){return xyt[e].map(t=>this._jointMeshes[Em.indexOf(t)])}getJointMesh(e){return this._jointMeshes[Em.indexOf(e)]}constructor(e,t,i,r,n=!1,a=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=n,this._jointsInvisible=a,this._jointScaleFactor=o,this.onHandMeshSetObservable=new Ae,this._jointTransforms=new Array(Em.length),this._jointTransformMatrices=new Float32Array(Em.length*16),this._tempJointMatrix=new he,this._jointRadii=new Float32Array(Em.length),this._scene=t[0].getScene();for(let l=0;l{l._doNotLoadControllerMesh=!0})}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(r=>{r.alwaysSelectAsActiveMesh=!0}),this._handMesh.skeleton){const r=this._handMesh.skeleton;Em.forEach((n,a)=>{const o=r.getBoneIndexByName(t?t[n]:n);o!==-1&&r.bones[o].linkTransformNode(this._jointTransforms[a])})}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const r=i,n=Em.map(o=>r[o]||i.get(o));let a=!1;if(e.fillPoses&&e.fillJointRadii)a=e.fillPoses(n,t,this._jointTransformMatrices)&&e.fillJointRadii(n,this._jointRadii);else if(e.getJointPose){a=!0;for(let o=0;o{const c=this._jointTransforms[l];he.FromArrayToRef(this._jointTransformMatrices,l*16,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,c.rotationQuaternion,c.position);const u=this._jointRadii[l]*this._jointScaleFactor,h=this._jointMeshes[l];h.isVisible=!this._handMesh&&!this._jointsInvisible,h.position.copyFrom(c.position),h.rotationQuaternion.copyFrom(c.rotationQuaternion),h.scaling.setAll(u),this._scene.useRightHandedSystem||(h.position.z*=-1,h.rotationQuaternion.z*=-1,h.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(c.position.z*=-1,c.rotationQuaternion.z*=-1,c.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){var t;this._handMesh&&(e?((t=this._handMesh.skeleton)==null||t.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class Bs extends gl{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var a,o,l,c,u;const r=[],n=((a=e.jointMeshes)==null?void 0:a.sourceMesh)||Uz("jointParent",Bs._ICOSPHERE_PARAMS);n.isVisible=!!((o=e.jointMeshes)!=null&&o.keepOriginalVisible);for(let h=0;h{var d,f,p,m,g,_;const n={};(f=(d=Bs._RightHandGLB)==null?void 0:d.meshes[1])!=null&&f.isDisposed()&&(Bs._RightHandGLB=null),(m=(p=Bs._LeftHandGLB)==null?void 0:p.meshes[1])!=null&&m.isDisposed()&&(Bs._LeftHandGLB=null);const a=!!(Bs._RightHandGLB&&Bs._LeftHandGLB),o=await Promise.all([Bs._RightHandGLB||Ys.ImportMeshAsync("",Bs.DEFAULT_HAND_MODEL_BASE_URL,Bs.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Bs._LeftHandGLB||Ys.ImportMeshAsync("",Bs.DEFAULT_HAND_MODEL_BASE_URL,Bs.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Bs._RightHandGLB=o[0],Bs._LeftHandGLB=o[1];const l=await Ss.ParseFromFileAsync("handShader",Bs.DEFAULT_HAND_MODEL_SHADER_URL,e);l.needDepthPrePass=!0,l.transparencyMode=Ye.MATERIAL_ALPHABLEND,l.alphaMode=2,l.build(!1);const c={base:Re.FromInts(116,63,203),fresnel:Re.FromInts(149,102,229),fingerColor:Re.FromInts(177,130,255),tipFresnel:Re.FromInts(220,200,255),...(g=i==null?void 0:i.handMeshes)==null?void 0:g.customColors},u={base:l.getBlockByName("baseColor"),fresnel:l.getBlockByName("fresnelColor"),fingerColor:l.getBlockByName("fingerColor"),tipFresnel:l.getBlockByName("tipFresnelColor")};u.base.value=c.base,u.fresnel.value=c.fresnel,u.fingerColor.value=c.fingerColor,u.tipFresnel.value=c.tipFresnel;const h=(_=t._getBaseLayerWrapper())==null?void 0:_.isMultiview;["left","right"].forEach(y=>{const v=y=="left"?Bs._LeftHandGLB:Bs._RightHandGLB;if(!v)throw new Error("Could not load hand model");const x=v.meshes[1];x._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,h||(x.material=l.clone(`${y}HandShaderClone`,!0)),x.isVisible=!1,n[y]=x,!a&&!e.useRightHandedSystem&&v.meshes[1].rotate(Da.Y,Math.PI)}),l.dispose(),r({left:n.left,right:n.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{wrist:`wrist_${t}`,"thumb-metacarpal":`thumb_metacarpal_${t}`,"thumb-phalanx-proximal":`thumb_proxPhalanx_${t}`,"thumb-phalanx-distal":`thumb_distPhalanx_${t}`,"thumb-tip":`thumb_tip_${t}`,"index-finger-metacarpal":`index_metacarpal_${t}`,"index-finger-phalanx-proximal":`index_proxPhalanx_${t}`,"index-finger-phalanx-intermediate":`index_intPhalanx_${t}`,"index-finger-phalanx-distal":`index_distPhalanx_${t}`,"index-finger-tip":`index_tip_${t}`,"middle-finger-metacarpal":`middle_metacarpal_${t}`,"middle-finger-phalanx-proximal":`middle_proxPhalanx_${t}`,"middle-finger-phalanx-intermediate":`middle_intPhalanx_${t}`,"middle-finger-phalanx-distal":`middle_distPhalanx_${t}`,"middle-finger-tip":`middle_tip_${t}`,"ring-finger-metacarpal":`ring_metacarpal_${t}`,"ring-finger-phalanx-proximal":`ring_proxPhalanx_${t}`,"ring-finger-phalanx-intermediate":`ring_intPhalanx_${t}`,"ring-finger-phalanx-distal":`ring_distPhalanx_${t}`,"ring-finger-tip":`ring_tip_${t}`,"pinky-finger-metacarpal":`little_metacarpal_${t}`,"pinky-finger-phalanx-proximal":`little_proxPhalanx_${t}`,"pinky-finger-phalanx-intermediate":`little_intPhalanx_${t}`,"pinky-finger-phalanx-distal":`little_distPhalanx_${t}`,"pinky-finger-tip":`little_tip_${t}`}}isCompatible(){return typeof XRHand<"u"}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return e=="none"?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new Ae,this.onHandRemovedObservable=new Ae,this._attachHand=n=>{var l,c,u;if(!n.inputSource.hand||n.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const a=n.inputSource.handedness,o=new vUe(n,this._handResources.jointMeshes[a],this._handResources.handMeshes&&this._handResources.handMeshes[a],this._handResources.rigMappings&&this._handResources.rigMappings[a],(l=this.options.handMeshes)==null?void 0:l.meshesUseLeftHandedCoordinates,(c=this.options.jointMeshes)==null?void 0:c.invisible,(u=this.options.jointMeshes)==null?void 0:u.scaleFactor);this._attachedHands[n.uniqueId]=o,this._trackingHands[a]=o,this.onHandAddedObservable.notifyObservers(o)},this._detachHand=n=>{this._detachHandById(n.uniqueId)},this.xrNativeFeatureName="hand-tracking";const r=t.jointMeshes;if(r&&(typeof r.disableDefaultHandMesh<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=r.disableDefaultHandMesh),typeof r.handMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=r.handMeshes),typeof r.leftHandedSystemMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=r.leftHandedSystemMeshes),typeof r.rigMapping<"u")){t.handMeshes=t.handMeshes||{};const n={},a={};[[r.rigMapping.left,n],[r.rigMapping.right,a]].forEach(o=>{const l=o[0],c=o[1];l.forEach((u,h)=>{c[Em[h]]=u})}),t.handMeshes.customRigMappings={left:n,right:a}}}attach(){var e,t,i,r;return super.attach()?(this._handResources={jointMeshes:Bs._GenerateTrackedJointMeshes(this.options),handMeshes:((e=this.options.handMeshes)==null?void 0:e.customMeshes)||null,rigMappings:((t=this.options.handMeshes)==null?void 0:t.customRigMappings)||null},!((i=this.options.handMeshes)!=null&&i.customMeshes)&&!((r=this.options.handMeshes)!=null&&r.disableDefaultMeshes)&&(Bs._GenerateDefaultHandMeshesAsync(Rt.LastCreatedScene,this._xrSessionManager,this.options).then(n=>{var a,o;this._handResources.handMeshes=n,this._handResources.rigMappings={left:Bs._GenerateDefaultHandMeshRigMapping("left"),right:Bs._GenerateDefaultHandMeshRigMapping("right")},(a=this._trackingHands.left)==null||a.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),(o=this._trackingHands.right)==null||o.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)}),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add(n=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(n.newScaleFactor/n.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(n.newScaleFactor/n.previousScaleFactor))})),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0):!1}_onXRFrame(e){var t,i;(t=this._trackingHands.left)==null||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),(i=this._trackingHands.right)==null||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){var r;const i=this.getHandByControllerId(e);if(i){const n=i.xrController.inputSource.handedness=="left"?"left":"right";((r=this._trackingHands[n])==null?void 0:r.xrController.uniqueId)===e&&(this._trackingHands[n]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){var e;return super.detach()?(Object.keys(this._attachedHands).forEach(t=>{var i;return this._detachHandById(t,(i=this.options.handMeshes)==null?void 0:i.disposeOnSessionEnd)}),(e=this.options.handMeshes)!=null&&e.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose())),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0):!1}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!((e=this.options.handMeshes)!=null&&e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Bs._RightHandGLB=null,Bs._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}Bs.Name=wr.HAND_TRACKING;Bs.Version=1;Bs.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";Bs.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";Bs.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";Bs.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";Bs._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};Bs._RightHandGLB=null;Bs._LeftHandGLB=null;Yn.AddWebXRFeature(Bs.Name,(s,e)=>()=>new Bs(s,e),Bs.Version,!1);var Xhe;(function(s){s[s.INIT=0]="INIT",s[s.STARTED=1]="STARTED",s[s.ENDED=2]="ENDED"})(Xhe||(Xhe={}));function vB(s){let e=0;const t=Date.now();s.observableParameters=s.observableParameters??{};const i=s.contextObservable.add(r=>{const n=Date.now();e=n-t;const a={startTime:t,currentTime:n,deltaTime:e,completeRate:e/s.timeout,payload:r};s.onTick&&s.onTick(a),s.breakCondition&&s.breakCondition()&&(s.contextObservable.remove(i),s.onAborted&&s.onAborted(a)),e>=s.timeout&&(s.contextObservable.remove(i),s.onEnded&&s.onEnded(a))},s.observableParameters.mask,s.observableParameters.insertFirst,s.observableParameters.scope);return i}class yUe{constructor(e){this.onEachCountObservable=new Ae,this.onTimerAbortedObservable=new Ae,this.onTimerEndedObservable=new Ae,this.onStateChangedObservable=new Ae,this._observer=null,this._breakOnNextTick=!1,this._tick=t=>{const i=Date.now();this._timer=i-this._startTime;const r={startTime:this._startTime,currentTime:i,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:t},n=this._breakOnNextTick||this._breakCondition(r);n||this._timer>=this._timeToEnd?this._stop(r,n):this.onEachCountObservable.notifyObservers(r)},this._setState(0),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===1)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(1)}stop(){this._state===1&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(2),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class PS extends gl{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,i=>i.name==="rotationCone");t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new Ze(1,1,1,1),this._tmpRay=new $i(new D,new D),this._tmpVector=new D,this._tmpQuaternion=new Pe,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new Ae,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new Ae,this.onAfterCameraTeleportRotation=new Ae,this._attachController=i=>{if(this._controllers[i.uniqueId]||this._options.forceHandedness&&i.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[i.uniqueId]={xrController:i,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const r=this._controllers[i.uniqueId];if(r.xrController.inputSource.targetRayMode==="tracked-pointer"&&r.xrController.inputSource.gamepad){const n=()=>{if(i.motionController){const a=i.motionController.getComponentOfType(id.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(id.TOUCHPAD_TYPE);if(!a||this._options.useMainComponentOnly){const o=i.motionController.getMainComponent();if(!o)return;r.teleportationState.mainComponentUsed=!0,r.teleportationComponent=o,r.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{if(!this.teleportationEnabled)return;const l=()=>{r.teleportationState.forward=!0,r.teleportationState.initialHit=!1,this._currentTeleportationControllerId=r.xrController.uniqueId,r.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,r.teleportationState.currentRotation=0;const c=this._options.timeToTeleport||3e3;vB({timeout:c,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!o.pressed,onEnded:()=>{this._currentTeleportationControllerId===r.xrController.uniqueId&&r.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};o.changes.pressed&&(o.changes.pressed.current?this._options.timeToTeleportStart?vB({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{o.pressed&&l()}}):l():(r.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else r.teleportationComponent=a,r.onAxisChangedObserver=a.onAxisValueChangedObservable.add(o=>{if(o.y<=.7&&r.teleportationState.backwards&&(r.teleportationState.backwards=!1),o.y>.7&&!r.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!r.teleportationState.backwards){r.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,Pe.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const l=this._xrSessionManager.scene.pickWithRay(this._tmpRay,c=>this._floorMeshes.indexOf(c)!==-1);l&&l.pickedPoint&&(this._options.xrInput.xrCamera.position.x=l.pickedPoint.x,this._options.xrInput.xrCamera.position.z=l.pickedPoint.z)}if(o.y<-.7&&!this._currentTeleportationControllerId&&!r.teleportationState.rotating&&this.teleportationEnabled&&(r.teleportationState.forward=!0,this._currentTeleportationControllerId=r.xrController.uniqueId,r.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),o.x){if(r.teleportationState.forward)this._currentTeleportationControllerId===r.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{r.teleportationState.currentRotation=Math.atan2(o.x,o.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):r.teleportationState.currentRotation=0);else if(!r.teleportationState.rotating&&Math.abs(o.x)>.7){r.teleportationState.rotating=!0;const l=this.rotationAngle*(o.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(l),Pe.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else r.teleportationState.rotating=!1;o.x===0&&o.y===0&&(r.teleportationState.blocked&&(r.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),r.teleportationState.forward&&this._teleportForward(i.uniqueId))})}};i.motionController?n():i.onMotionControllerInitObservable.addOnce(()=>{n()})}else{r.teleportationState.mainComponentUsed=!0;let n=!1;const a=()=>{this._currentTeleportationControllerId=r.xrController.uniqueId,r.teleportationState.forward=!0,r.teleportationState.initialHit=!1,r.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,r.teleportationState.currentRotation=0;const o=this._options.timeToTeleport||3e3;vB({timeout:o,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===r.xrController.uniqueId&&r.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add(o=>{o.type===yt.POINTERDOWN?(n=!1,this._options.timeToTeleportStart?vB({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===r.xrController.uniqueId&&a()},breakCondition:()=>n?(n=!1,!0):!1}):a()):o.type===yt.POINTERUP&&(n=!0,r.teleportationState.forward=!1,this._currentTeleportationControllerId="")})}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ze(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add(i=>{var r;this.parabolicCheckRadius=this.parabolicCheckRadius/i.previousScaleFactor*i.newScaleFactor,(r=this._options.teleportationTargetMesh)==null||r.scaling.scaleInPlace(i.newScaleFactor/i.previousScaleFactor)})}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return super.attach()?(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0):!1}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);t!==-1&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);t!==-1&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(t===-1){for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(u)||this._options.blockAllPickableMeshes&&u.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(u)!==-1)return!0;const h=this._floorMeshes.indexOf(u);return h===-1?!1:this._floorMeshes[h].absolutePosition.ythis._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(f)||this._options.blockAllPickableMeshes&&f.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(f)!==-1?!0:this._floorMeshes.indexOf(f)!==-1),d=h&&h.pickedMesh&&this._floorMeshes.indexOf(h.pickedMesh)!==-1;if(h&&h.pickedMesh&&!d){if(n.teleportationState.mainComponentUsed&&!n.teleportationState.initialHit){n.teleportationState.forward=!1;return}n.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,o),this._showParabolicPath(h);return}else h&&h.pickedPoint&&(n.teleportationState.initialHit=!0,n.teleportationState.blocked=!1,a=!0,this._setTargetMeshPosition(h),this._setTargetMeshVisibility(!0,!1,o),this._showParabolicPath(h))}this._setTargetMeshVisibility(a,!1,o)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||is.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=aT("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const a=new Qf("teleportationPlaneDynamicTexture",512,e,!0);a.hasAlpha=!0;const o=a.getContext(),l=512/2,c=512/2,u=200;o.beginPath(),o.arc(l,c,u,0,2*Math.PI,!1),o.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",o.fill(),o.lineWidth=10,o.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",o.stroke(),o.closePath(),a.update();const h=new et("teleportationPlaneMaterial",e);h.diffuseTexture=a,t.material=h}const i=ug("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const n=new tt("animationInnerCircle","position.y",30,tt.ANIMATIONTYPE_FLOAT,tt.ANIMATIONLOOPMODE_CYCLE),a=[];a.push({frame:0,value:0}),a.push({frame:30,value:.4}),a.push({frame:60,value:0}),n.setKeys(a);const o=new Age;o.setEasingMode(ya.EASINGMODE_EASEINOUT),n.setEasingFunction(o),i.animations=[],i.animations.push(n),e.beginAnimation(i,0,60,!0)}const r=ou("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(Da.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const n=new et("torusConsMat",e);n.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,n.disableLighting?n.emissiveColor=new Re(.3,.3,1):n.diffuseColor=new Re(.3,.3,1),n.alpha=.9,i.material=n,r.material=n,this._teleportationRingMaterial=n}this._options.renderingGroupId!==void 0&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){const n=t*t;this._snapToPositions.forEach(a=>{const o=D.DistanceSquared(a,e);o<=n&&o{r.isVisible=e}),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach())))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||is.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Jp.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),n=i.teleportationState.blocked?this._blockedRayColor:void 0,a=this._colorArray.fill(n||this._cachedColor4White),o=r.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=dn("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:a},t),this._quadraticBezierCurve.isPickable=!1,this._options.renderingGroupId!==void 0&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(!(!t||!t.teleportationState.forward||!this.teleportationEnabled)&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!(this.snapPointsOnly&&!this._snappedToPoint))){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const i=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,Pe.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}PS.Name=wr.TELEPORTATION;PS.Version=1;Yn.AddWebXRFeature(PS.Name,(s,e)=>()=>new PS(s,e),PS.Version,!0);class Ayt{}class _ee{constructor(){}static CreateAsync(e,t={}){const i=new _ee;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const r={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&(typeof t.optionalFeatures=="boolean"?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new gee(e,r)}return pee.CreateAsync(e).then(r=>{if(i.baseExperience=r,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new mUe(r.sessionManager,r.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const n={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(eg.Name,t.useStablePlugins?"stable":"latest",n),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(PS.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}if(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(tg.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(Bs.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),!t.disableDefaultUI)return i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(r=>(fe.Error("Error initializing XR"),fe.Error(r),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var byt=!0;gt.prototype.createDefaultLight=function(s=!1){if(s&&this.lights)for(let e=0;el.isVisible&&l.isEnabled()),r=i.max.subtract(i.min),n=i.min.add(r.scale(.5));let a,o=r.length()*1.5;if(isFinite(o)||(o=1,n.copyFromFloats(0,0,0)),s){const l=new Kr("default camera",-(Math.PI/2),Math.PI/2,o,n,this);l.lowerRadiusLimit=o*.01,l.wheelPrecision=100/o,a=l}else{const l=new Dl("default camera",new D(n.x,n.y,-o),this);l.setTarget(n),a=l}a.minZ=o*.01,a.maxZ=o*1e3,a.speed=o*.2,this.activeCamera=a,t&&a.attachControl()}};gt.prototype.createDefaultCameraOrLight=function(s=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(s,e,t)};gt.prototype.createDefaultSkybox=function(s,e=!1,t=1e3,i=0,r=!0){if(!s)return fe.Warn("Can not create default skybox without environment texture."),null;r&&s&&(this.environmentTexture=s);const n=ph("hdrSkyBox",{size:t},this);if(e){const a=new Lt("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=s.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=xe.SKYBOX_MODE),a.microSurface=1-i,a.disableLighting=!0,a.twoSidedLighting=!0,n.material=a}else{const a=new et("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=s.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=xe.SKYBOX_MODE),a.disableLighting=!0,n.material=a}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n};gt.prototype.createDefaultEnvironment=function(s){return Sx?new Sx(s,this):null};gt.prototype.createDefaultVRExperience=function(s={}){return new t6(this,s)};gt.prototype.createDefaultXRExperienceAsync=function(s={}){return _ee.CreateAsync(this,s).then(e=>e)};function rMe(s){for(;s.firstChild;)s.removeChild(s.firstChild);s.srcObject=null,s.src="",s.removeAttribute("src")}class yh extends xe{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new Ae),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):fe.Error(e==null?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((e==null?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}else if(!this.video.muted){fe.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(t=>{this._processError(t)});return}}this._processError(e)})}constructor(e,t,i,r=!1,n=!1,a=xe.TRILINEAR_SAMPLINGMODE,o={},l,c=5){super(null,i,!r,n),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{this._texture!=null&&this._texture.dispose(),!this._getEngine().needPOTTextures||Me.IsExponentOfTwo(this.video.videoWidth)&&Me.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=xe.WRAP_ADDRESSMODE,this.wrapV=xe.WRAP_ADDRESSMODE):(this.wrapU=xe.CLAMP_ADDRESSMODE,this.wrapV=xe.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(this._texture!=null)if(this._displayingPosterTexture)this._displayingPosterTexture=!1;else return;if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),!this.video.autoplay&&!this._settings.poster&&!this._settings.independentVideoSource){const f=this.video.onplaying,p=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=p,this.video.onplaying=f,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}else this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._reset=()=>{this._texture!=null&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(this._texture==null||this.video.readyState=this.video.HAVE_CURRENT_DATA;this._settings.poster&&(!this._settings.autoPlay||!d)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):d&&this._createInternalTexture()}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:typeof e=="object"?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Me.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(Me.SetCorsBehavior(e,t),t.src=e):(Me.SetCorsBehavior(e[0],t),e.forEach(i=>{const r=document.createElement("source");r.src=i,t.appendChild(r)})),this.onDisposeObservable.addOnce(()=>{rMe(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new yh(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),(e=this._externalTexture)==null||e.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){const n=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(n),n.style.transform="scale(0.0001, 0.0001)",n.style.opacity="0",n.style.position="fixed",n.style.bottom="0px",n.style.right="0px"),n.setAttribute("autoplay",""),n.setAttribute("muted","true"),n.setAttribute("playsinline",""),n.muted=!0,n.isNative||(n.mozSrcObject!==void 0?n.mozSrcObject=t:typeof n.srcObject=="object"?n.srcObject=t:n.src=window.URL&&window.URL.createObjectURL(t)),new Promise(a=>{const o=()=>{const l=new yh("video",n,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{n.remove()}),l.onDisposeObservable.addOnce(()=>{rMe(n)}),a(l),n.removeEventListener("playing",o)};n.addEventListener("playing",o),n.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){const n=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),a=await this.CreateFromStreamAsync(e,n,t,r);return a.onDisposeObservable.addOnce(()=>{n.getTracks().forEach(o=>{o.stop()})}),a}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,n=!0){this.CreateFromWebCamAsync(e,i,r,n).then(function(a){t&&t(a)}).catch(function(a){fe.Error(a.name)})}}F([X("settings")],yh.prototype,"_settings",void 0);F([X("src")],yh.prototype,"_currentSrc",void 0);F([X()],yh.prototype,"isVideo",void 0);xe._CreateVideoTexture=(s,e,t,i=!1,r=!1,n=xe.TRILINEAR_SAMPLINGMODE,a={},o,l=5)=>new yh(s,e,t,i,r,n,a,o,l);ve("BABYLON.VideoTexture",yh);class vee extends _h{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},n=new yh((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,xe.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(a=>{var o;((o=a.pickInfo)==null?void 0:o.pickedMesh)===this.mesh&&this._texture.video.play()},yt.POINTERDOWN)),this._textureObserver=n.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),n}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}vee.MODE_MONOSCOPIC=_h.MODE_MONOSCOPIC;vee.MODE_TOPBOTTOM=_h.MODE_TOPBOTTOM;vee.MODE_SIDEBYSIDE=_h.MODE_SIDEBYSIDE;class xUe{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add(()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()}),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add(()=>{this._shaderCompilationTime.endMonitoring()})):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new io,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class AUe{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add(()=>{Me.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(()=>{Me.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)})):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add(()=>{Me.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(()=>{Me.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)})):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add(()=>{Me.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(()=>{Me.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add(()=>{Me.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(()=>{Me.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add(()=>{Me.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(()=>{Me.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()})):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add(()=>{this._animationsTime.endMonitoring()}):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add(()=>{this._renderTime.beginMonitoring(),Me.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(()=>{this._renderTime.endMonitoring(!1),Me.EndPerformanceCounter("Main render")})):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add(t=>{this._cameraRenderTime.beginMonitoring(),Me.StartPerformanceCounter(`Rendering camera ${t.name}`)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(t=>{this._cameraRenderTime.endMonitoring(!1),Me.EndPerformanceCounter(`Rendering camera ${t.name}`)})):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new io,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new io,this._captureFrameTime=!1,this._frameTime=new io,this._captureRenderTime=!1,this._renderTime=new io,this._captureInterFrameTime=!1,this._interFrameTime=new io,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new io,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new io,this._capturePhysicsTime=!1,this._physicsTime=new io,this._captureAnimationsTime=!1,this._animationsTime=new io,this._captureCameraRenderTime=!1,this._cameraRenderTime=new io,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add(()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(Me.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()}),this._onAfterRenderObserver=e.onAfterRenderObservable.add(()=>{this._captureFrameTime&&(Me.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()})}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}class Ah{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||t===0)&&e.subMeshes)for(let r=0;r{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n;const a=this._scene.getEngine();if(r.length){for(a.setColorWrite(!1),n=0;n{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var y;const r=this._scene.getEngine(),n=e.getMesh(),a=(y=n._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:y[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const l=[],c=[$.PositionKind];let u=!1,h=!1;if(o){const v=o.needAlphaTesting(),x=o.getAlphaTestTexture(),A=x&&x.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);x&&(v||A)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent($.UV2Kind)&&x.coordinatesIndex===1?(l.push("#define DIFFUSEUV2"),h=!0):n.isVerticesDataPresent($.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),v&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),x.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const b=o.opacityTexture;b&&(l.push("#define OPACITY"),n.isVerticesDataPresent($.UV2Kind)&&b.coordinatesIndex===1?(l.push("#define OPACITYUV2"),h=!0):n.isVerticesDataPresent($.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent($.UV2Kind)&&i.coordinatesIndex===1?(l.push("#define EMISSIVEUV2"),h=!0):n.isVerticesDataPresent($.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent($.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==Ye.MATERIAL_OPAQUE&&(c.push($.ColorKind),l.push("#define VERTEXALPHA")),u&&(c.push($.UVKind),l.push("#define UV1")),h&&(c.push($.UV2Kind),l.push("#define UV2"));const d=new oa;if(n.useBones&&n.computeBonesUsingShaders){c.push($.MatricesIndicesKind),c.push($.MatricesWeightsKind),n.numBoneInfluencers>4&&(c.push($.MatricesIndicesExtraKind),c.push($.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);const v=n.skeleton;v&&v.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(v?v.bones.length+1:0)),n.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");const f=n.morphTargetManager;let p=0;f&&(p=f.numMaxInfluencers||f.numInfluencers,p>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+p),f.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),rT(c,n,p))),t&&(l.push("#define INSTANCES"),A_(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),t3(o,this._scene,l),this._addCustomEffectDefines(l);const m=e._getDrawWrapper(void 0,!0),g=m.defines,_=l.join(` `);if(g!==_){const v=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];fo(v),m.setEffect(this._engine.createEffect("glowMapGeneration",c,v,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],_,d,void 0,void 0,{maxSimultaneousMorphTargets:p},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),_)}return m.effect.isReady()}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>Oyt),void 0),Ue(()=>Promise.resolve().then(()=>wyt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>Ryt),void 0),Ue(()=>Promise.resolve().then(()=>Eyt),void 0)])}render(){for(let a=0;ay.setMatrix("world",x))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[$.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return Me.Instantiate(e.customType).Parse(e,t,i)}}Ah.ForceGLSL=!1;Ah._SceneComponentInitialization=s=>{throw vi("EffectLayerSceneComponent")};F([X()],Ah.prototype,"name",void 0);F([jw()],Ah.prototype,"neutralColor",void 0);F([X()],Ah.prototype,"isEnabled",void 0);F([GFe()],Ah.prototype,"camera",null);F([X()],Ah.prototype,"renderingGroupId",null);F([X()],Ah.prototype,"disableBoundingBoxesFromEffectLayer",void 0);Oa.AddParser(ot.NAME_EFFECTLAYER,(s,e,t,i)=>{if(s.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(t)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(i=>{this.scene.removeEffectLayer(i),t&&i.dispose()})}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(const n of r){if(!n.hasMesh(e))continue;const a=n._mainTexture;this._engine.currentRenderPassId=a.renderPassId;for(const o of e.subMeshes)if(!n.isReady(o,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===Nt.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==Nt.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();const n=r._mainTexture;n._shouldRender()&&(this.scene.incrementRenderId(),n.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let e=s._getComponent(ot.NAME_EFFECTLAYER);e||(e=new bUe(s),s._addComponent(e))};Oa.prototype.getGlowLayerByName=function(s){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===s&&this.effectLayers[t].getEffectName()===ao.EffectName)return this.effectLayers[t];return null};class ao extends Ah{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;const t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new Ze(0,0,0,1),this._options={mainTextureRatio:ao.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>Eze),void 0),Ue(()=>Promise.resolve().then(()=>Ize),void 0),Ue(()=>Promise.resolve().then(()=>V1e),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>pze),void 0),Ue(()=>Promise.resolve().then(()=>vze),void 0),Ue(()=>Promise.resolve().then(()=>z1e),void 0)]),await super._importShadersAsync()}getEffectName(){return ao.EffectName}_createMergeEffect(){let e=`#define EMISSIVE `;return this._options.ldrMerge&&(e+=`#define LDR `),this._engine.createEffect("glowMapMerge",[$.PositionKind],["offset"],["textureSampler","textureSampler2"],e,void 0,void 0,void 0,void 0,this.shaderLanguage)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?ad(e,this._maxSize):e,t=this._engine.needPOTTextures?ad(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new Rs("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=xe.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=xe.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(xe.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const r=Math.floor(e/2),n=Math.floor(t/2);this._blurTexture2=new Rs("GlowLayerBlurRTT2",{width:r,height:n},this._scene,!1,!0,i),this._blurTexture2.wrapU=xe.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=xe.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(xe.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const a=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new Ho("GlowLayerHBP1",new we(1,0),a,{width:e,height:t},null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new Ho("GlowLayerVBP1",new we(0,1),a,{width:e,height:t},null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Ho("GlowLayerHBP2",new we(1,0),a,{width:r,height:n},null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=n,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new Ho("GlowLayerVBP2",new we(0,1),a,{width:r,height:n},null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{const o=this._blurTexture1.renderTarget;if(o){this._scene.postProcessManager.directRender(this._postProcesses1,o,!0);const l=this._blurTexture2.renderTarget;l&&this._scene.postProcessManager.directRender(this._postProcesses2,l,!0),this._engine.unBindFramebuffer(l??o,!0)}}),this._postProcesses.map(o=>{o.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;const n=i.emissiveTexture;return super._isReady(e,t,n)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Ye.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let r=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(r=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const n=i.emissiveIntensity??1;r*=n,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*r,i.emissiveColor.g*r,i.emissiveColor.b*r,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){this._includedOnlyMeshes.indexOf(e.uniqueId)===-1&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);t!==-1&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return super.hasMesh(e)?this._includedOnlyMeshes.length?this._includedOnlyMeshes.indexOf(e.uniqueId)!==-1:this._excludedMeshes.length?this._excludedMeshes.indexOf(e.uniqueId)===-1:!0:!1}_useMeshMaterial(e){return this._meshesUsingTheirOwnMaterials.length==0?!1:this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=qe.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew ao(e.name,t,e.options),e,t,i);let n;for(n=0;n{c.setFloat2("screenSize",this.width,this.height),c.setVector2("direction",this.direction),c.setFloat("blurWidth",this.kernel)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>V1e),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>z1e),void 0)),super._gatherImports(e,t)}}class Lc extends Ah{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t,i!==void 0?!!i.forceGLSL:!1),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new Ae,this.onAfterBlurObservable=new Ae,this._instanceGlowingMeshStencilReference=Lc.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Lc.NeutralColor,this._engine.isStencilEnable||fe.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,forceGLSL:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>Eze),void 0),Ue(()=>Promise.resolve().then(()=>Ize),void 0),Ue(()=>Promise.resolve().then(()=>V1e),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>pze),void 0),Ue(()=>Promise.resolve().then(()=>vze),void 0),Ue(()=>Promise.resolve().then(()=>z1e),void 0)]),await super._importShadersAsync()}getEffectName(){return Lc.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[$.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE `:void 0,void 0,void 0,void 0,void 0,this._shaderLanguage)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?ad(e,this._maxSize):e,t=this._engine.needPOTTextures?ad(t,this._maxSize):t;let i=0;if(this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new Rs("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=xe.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=xe.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(xe.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2)this._downSamplePostprocess=new D0("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new sMe("HighlightLayerHBP",new we(1,0),this._options.blurHorizontalSize,1,null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new sMe("HighlightLayerVBP",new we(0,1),this._options.blurVerticalSize,1,null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess];else{this._horizontalBlurPostprocess=new Ho("HighlightLayerHBP",new we(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i);const r=this._horizontalBlurPostprocess;r.width=e,r.height=t,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(n=>{n.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new Ho("HighlightLayerVBP",new we(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]}this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const r=this._blurTexture.renderTarget;r&&(this._scene.postProcessManager.directRender(this._postProcesses,r,!0),this._engine.unBindFramebuffer(r,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(r=>{r.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let n=null;const a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(n=i.emissiveTexture),super._isReady(e,t,n)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Ye.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ye.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return super.shouldRender()?!!this._meshes:!1}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){const i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(r=>{i.stencilState=r.getEngine().getStencilBuffer(),r.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(r=>{r.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:this._meshes[e.uniqueId]!==void 0&&this._meshes[e.uniqueId]!==null}addMesh(e,t,i=!1){if(!this._meshes)return;const r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(n=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[n.uniqueId]?this._defaultStencilReference(n):n.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(n=>{this.isEnabled&&this._defaultStencilReference(n)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Lc.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=qe.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const r=qe.Parse(()=>new Lc(e.name,t,e.options),e,t,i);let n;for(n=0;nthis._drawCameraPredicate(t,!0,!0,e.layerMask))}_drawCameraForegroundWithPostProcessing(e){this._draw(t=>this._drawCameraPredicate(t,!1,!0,e.layerMask))}_drawCameraForegroundWithoutPostProcessing(e){this._draw(t=>this._drawCameraPredicate(t,!1,!1,e.layerMask))}_drawRenderTargetPredicate(e,t,i,r,n){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(n)>-1&&(e.layerMask&r)!==0}_drawRenderTargetBackground(e){this._draw(t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw(t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw(t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e))}addFromContainer(e){e.layers&&e.layers.forEach(t=>{this.scene.layers.push(t)})}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach(i=>{const r=this.scene.layers.indexOf(i);r!==-1&&this.scene.layers.splice(r,1),t&&i.dispose()})}}let yee=class SUe{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,n,a=!1){this.name=e,this._applyPostProcess=!0,this.scale=new we(1,1),this.offset=new we(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new Ae,this.onBeforeRenderObservable=new Ae,this.onAfterRenderObservable=new Ae,this._shaderLanguage=0,this._shadersLoaded=!1,this.texture=t?new xe(t,i,!0):null,this.isBackground=r===void 0?!0:r,this.color=n===void 0?new Ze(1,1,1,1):n,this._scene=i||Rt.LastCreatedScene;const o=this._scene.getEngine();o.isWebGPU&&!a&&!SUe.ForceGLSL&&(this._shaderLanguage=1);let l=this._scene._getComponent(ot.NAME_LAYER);l||(l=new CUe(this._scene),this._scene._addComponent(l)),this._scene.layers.push(this),this._drawWrapper=new Ro(o);const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1);const u=new $(o,c,$.PositionKind,!1,!1,2);this._vertexBuffers[$.PositionKind]=u,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[$.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+=` #define LINEAR`),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[$.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>kyt),void 0),Ue(()=>Promise.resolve().then(()=>Byt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>Fyt),void 0),Ue(()=>Promise.resolve().then(()=>Nyt),void 0)]),this._shadersLoaded=!0}));const i=this._drawWrapper.effect;return(i==null?void 0:i.isReady())&&(!this.texture||this.texture.isReady())}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),this.texture&&(t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix())),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Ye.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Ye.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[$.PositionKind];e&&(e.dispose(),this._vertexBuffers[$.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}};yee.ForceGLSL=!1;const EUe="helperFunctions",TUe=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; #define saturate(x) clamp(x,0.0,1.0) #define absEps(x) abs(x)+Epsilon #define maxEps(x) max(x,Epsilon) #define saturateEps(x) clamp(x,Epsilon,1.0) mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( vec3(i0.x,i1.x,i2.x), vec3(i0.y,i1.y,i2.y), vec3(i0.z,i1.z,i2.z) );return outMatrix;} mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} #if USE_EXACT_SRGB_CONVERSIONS vec3 toLinearSpaceExact(vec3 color) {vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); #else return vec3( color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); #endif } vec3 toGammaSpaceExact(vec3 color) {vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); #else return vec3( color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); #endif } #endif float toLinearSpace(float color) { #if USE_EXACT_SRGB_CONVERSIONS float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; #else return pow(color,LinearEncodePowerApprox); #endif } vec3 toLinearSpace(vec3 color) { #if USE_EXACT_SRGB_CONVERSIONS return toLinearSpaceExact(color); #else return pow(color,vec3(LinearEncodePowerApprox)); #endif } vec4 toLinearSpace(vec4 color) { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toLinearSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); #endif } float toGammaSpace(float color) { #if USE_EXACT_SRGB_CONVERSIONS float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; #else return pow(color,GammaEncodePowerApprox); #endif } vec3 toGammaSpace(vec3 color) { #if USE_EXACT_SRGB_CONVERSIONS return toGammaSpaceExact(color); #else return pow(color,vec3(GammaEncodePowerApprox)); #endif } vec4 toGammaSpace(vec4 color) { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toGammaSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); #endif } float square(float value) {return value*value;} vec3 square(vec3 value) {return value*value;} float pow5(float value) {float sq=value*value;return sq*sq*value;} float getLuminance(vec3 color) {return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} `;de.IncludesShadersStore[EUe]=TUe;const MUe={name:EUe,shader:TUe},RUe=Object.freeze(Object.defineProperty({__proto__:null,helperFunctions:MUe},Symbol.toStringTag,{value:"Module"})),IUe="clipPlaneFragmentDeclaration",PUe=`#ifdef CLIPPLANE varying float fClipDistance; #endif #ifdef CLIPPLANE2 varying float fClipDistance2; #endif #ifdef CLIPPLANE3 varying float fClipDistance3; #endif #ifdef CLIPPLANE4 varying float fClipDistance4; #endif #ifdef CLIPPLANE5 varying float fClipDistance5; #endif #ifdef CLIPPLANE6 varying float fClipDistance6; #endif `;de.IncludesShadersStore[IUe]=PUe;const wUe={name:IUe,shader:PUe},Cyt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentDeclaration:wUe},Symbol.toStringTag,{value:"Module"})),DUe="clipPlaneFragment",LUe=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE else if (fClipDistance>0.0) {discard;} #endif #ifdef CLIPPLANE2 else if (fClipDistance2>0.0) {discard;} #endif #ifdef CLIPPLANE3 else if (fClipDistance3>0.0) {discard;} #endif #ifdef CLIPPLANE4 else if (fClipDistance4>0.0) {discard;} #endif #ifdef CLIPPLANE5 else if (fClipDistance5>0.0) {discard;} #endif #ifdef CLIPPLANE6 else if (fClipDistance6>0.0) {discard;} #endif `;de.IncludesShadersStore[DUe]=LUe;const OUe={name:DUe,shader:LUe},Syt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragment:OUe},Symbol.toStringTag,{value:"Module"})),NUe="glowMapGenerationPixelShader",FUe=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; #endif #ifdef OPACITY varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; #endif #ifdef EMISSIVE varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; #endif #ifdef VERTEXALPHA varying vec4 vColor; #endif uniform vec4 glowColor;uniform float glowIntensity; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include vec4 finalColor=glowColor; #ifdef DIFFUSE vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); #ifdef DIFFUSE_ISLINEAR albedoTexture=toGammaSpace(albedoTexture); #endif #ifdef GLOW finalColor.a*=albedoTexture.a; #endif #ifdef HIGHLIGHT finalColor.a=albedoTexture.a; #endif #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); #ifdef OPACITYRGB finalColor.a*=getLuminance(opacityMap.rgb); #else finalColor.a*=opacityMap.a; #endif finalColor.a*=opacityIntensity; #endif #ifdef VERTEXALPHA finalColor.a*=vColor.a; #endif #ifdef ALPHATEST if (finalColor.a #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform mat4 viewProjection;varying vec4 vPosition; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #ifdef DIFFUSE varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; #endif #ifdef OPACITY varying vec2 vUVOpacity;uniform mat4 opacityMatrix; #endif #ifdef EMISSIVE varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; #endif #ifdef VERTEXALPHA attribute vec4 color;varying vec4 vColor; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef CUBEMAP vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); #else vPosition=viewProjection*worldPos;gl_Position=vPosition; #endif #ifdef DIFFUSE #ifdef DIFFUSEUV1 vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef DIFFUSEUV2 vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #ifdef OPACITY #ifdef OPACITYUV1 vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef OPACITYUV2 vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); #endif #endif #ifdef EMISSIVE #ifdef EMISSIVEUV1 vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef EMISSIVEUV2 vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); #endif #endif #ifdef VERTEXALPHA vColor=color; #endif #include }`;de.ShadersStore[KUe]=HUe;const jUe={name:KUe,shader:HUe},Ryt=Object.freeze(Object.defineProperty({__proto__:null,glowMapGenerationVertexShader:jUe},Symbol.toStringTag,{value:"Module"})),XUe="clipPlaneFragmentDeclaration",YUe=`#ifdef CLIPPLANE varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 varying fClipDistance2: f32; #endif #ifdef CLIPPLANE3 varying fClipDistance3: f32; #endif #ifdef CLIPPLANE4 varying fClipDistance4: f32; #endif #ifdef CLIPPLANE5 varying fClipDistance5: f32; #endif #ifdef CLIPPLANE6 varying fClipDistance6: f32; #endif `;de.IncludesShadersStoreWGSL[XUe]=YUe;const QUe={name:XUe,shader:YUe},Iyt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentDeclarationWGSL:QUe},Symbol.toStringTag,{value:"Module"})),$Ue="clipPlaneFragment",ZUe=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE else if (fragmentInputs.fClipDistance>0.0) {discard;} #endif #ifdef CLIPPLANE2 else if (fragmentInputs.fClipDistance2>0.0) {discard;} #endif #ifdef CLIPPLANE3 else if (fragmentInputs.fClipDistance3>0.0) {discard;} #endif #ifdef CLIPPLANE4 else if (fragmentInputs.fClipDistance4>0.0) {discard;} #endif #ifdef CLIPPLANE5 else if (fragmentInputs.fClipDistance5>0.0) {discard;} #endif #ifdef CLIPPLANE6 else if (fragmentInputs.fClipDistance6>0.0) {discard;} #endif `;de.IncludesShadersStoreWGSL[$Ue]=ZUe;const qUe={name:$Ue,shader:ZUe},Pyt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentWGSL:qUe},Symbol.toStringTag,{value:"Module"})),JUe="glowMapGenerationPixelShader",eze=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE varying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #ifdef OPACITY varying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d;uniform var opacityIntensity: f32; #endif #ifdef EMISSIVE varying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d; #endif #ifdef VERTEXALPHA varying vColor: vec4f; #endif uniform glowColor: vec4f;uniform glowIntensity: f32; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include var finalColor: vec4f=uniforms.glowColor; #ifdef DIFFUSE var albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse); #ifdef DIFFUSE_ISLINEAR albedoTexture=toGammaSpace(albedoTexture); #endif #ifdef GLOW finalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a); #endif #ifdef HIGHLIGHT finalColor=vec4f(finalColor.rgb,albedoTexture.a); #endif #endif #ifdef OPACITY var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity); #ifdef OPACITYRGB finalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb)); #else finalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a); #endif finalColor=vec4f(finalColor.rgb,finalColor.a*opacityIntensity); #endif #ifdef VERTEXALPHA finalColor=vec4f(finalColor.rgb,finalColor.a*vColor.a); #endif #ifdef ALPHATEST if (finalColor.a;varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 uniform vClipPlane2: vec4;varying fClipDistance2: f32; #endif #ifdef CLIPPLANE3 uniform vClipPlane3: vec4;varying fClipDistance3: f32; #endif #ifdef CLIPPLANE4 uniform vClipPlane4: vec4;varying fClipDistance4: f32; #endif #ifdef CLIPPLANE5 uniform vClipPlane5: vec4;varying fClipDistance5: f32; #endif #ifdef CLIPPLANE6 uniform vClipPlane6: vec4;varying fClipDistance6: f32; #endif `;de.IncludesShadersStoreWGSL[ize]=rze;const sze={name:ize,shader:rze},Dyt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneVertexDeclarationWGSL:sze},Symbol.toStringTag,{value:"Module"})),nze="clipPlaneVertex",aze=`#ifdef CLIPPLANE vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); #endif #ifdef CLIPPLANE2 vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); #endif #ifdef CLIPPLANE3 vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); #endif #ifdef CLIPPLANE4 vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); #endif #ifdef CLIPPLANE5 vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); #endif #ifdef CLIPPLANE6 vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); #endif `;de.IncludesShadersStoreWGSL[nze]=aze;const oze={name:nze,shader:aze},Lyt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneVertexWGSL:oze},Symbol.toStringTag,{value:"Module"})),lze="glowMapGenerationVertexShader",cze=`attribute position: vec3f; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform viewProjection: mat4x4f;varying vPosition: vec4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #ifdef DIFFUSE varying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f; #endif #ifdef OPACITY varying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f; #endif #ifdef EMISSIVE varying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f; #endif #ifdef VERTEXALPHA attribute color: vec4f;varying vColor: vec4f; #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); #ifdef CUBEMAP vertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(input.position,1.0); #else vertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition; #endif #ifdef DIFFUSE #ifdef DIFFUSEUV1 vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef DIFFUSEUV2 vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #endif #ifdef OPACITY #ifdef OPACITYUV1 vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef OPACITYUV2 vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #endif #ifdef EMISSIVE #ifdef EMISSIVEUV1 vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef EMISSIVEUV2 vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #endif #ifdef VERTEXALPHA vertexOutputs.vColor=color; #endif #include }`;de.ShadersStoreWGSL[lze]=cze;const uze={name:lze,shader:cze},Oyt=Object.freeze(Object.defineProperty({__proto__:null,glowMapGenerationVertexShaderWGSL:uze},Symbol.toStringTag,{value:"Module"})),hze="glowMapMergePixelShader",dze=`varying vec2 vUV;uniform sampler2D textureSampler; #ifdef EMISSIVE uniform sampler2D textureSampler2; #endif uniform float offset; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV); #ifdef EMISSIVE baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; #else baseColor.a=abs(offset-baseColor.a); #ifdef STROKE float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; #endif #endif #if LDR baseColor=clamp(baseColor,0.,1.0); #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[hze]=dze;const fze={name:hze,shader:dze},pze=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergePixelShader:fze},Symbol.toStringTag,{value:"Module"})),mze="glowMapMergeVertexShader",gze=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[mze]=gze;const _ze={name:mze,shader:gze},vze=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergeVertexShader:_ze},Symbol.toStringTag,{value:"Module"})),yze="glowBlurPostProcessPixelShader",xze=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) {return dot(color,vec3(0.2126,0.7152,0.0722));} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) {vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} gl_FragColor=baseColor;}`;de.ShadersStore[yze]=xze;const Aze={name:yze,shader:xze},z1e=Object.freeze(Object.defineProperty({__proto__:null,glowBlurPostProcessPixelShader:Aze},Symbol.toStringTag,{value:"Module"})),bze="glowMapMergePixelShader",Cze=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #ifdef EMISSIVE var textureSampler2Sampler: sampler;var textureSampler2: texture_2d; #endif uniform offset: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); #ifdef EMISSIVE baseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset; #else baseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a)); #ifdef STROKE var alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha); #endif #endif #if LDR baseColor=clamp(baseColor,0.,1.0); #endif fragmentOutputs.color=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[bze]=Cze;const Sze={name:bze,shader:Cze},Eze=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergePixelShaderWGSL:Sze},Symbol.toStringTag,{value:"Module"})),Tze="glowMapMergeVertexShader",Mze=`attribute position: vec2f;varying vUV: vec2f; #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[Tze]=Mze;const Rze={name:Tze,shader:Mze},Ize=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergeVertexShaderWGSL:Rze},Symbol.toStringTag,{value:"Module"})),Pze="glowBlurPostProcessPixelShader",wze=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32 {return dot(color, vec3f(0.2126,0.7152,0.0722));} #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var weights: array;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++) {var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;} fragmentOutputs.color=baseColor;}`;de.ShadersStoreWGSL[Pze]=wze;const Dze={name:Pze,shader:wze},V1e=Object.freeze(Object.defineProperty({__proto__:null,glowBlurPostProcessPixelShaderWGSL:Dze},Symbol.toStringTag,{value:"Module"})),Lze="layerPixelShader",Oze=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV); #ifdef LINEAR baseColor.rgb=toGammaSpace(baseColor.rgb); #endif #ifdef ALPHATEST if (baseColor.a<0.4) discard; #endif gl_FragColor=baseColor*color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[Lze]=Oze;const Nze={name:Lze,shader:Oze},Nyt=Object.freeze(Object.defineProperty({__proto__:null,layerPixelShader:Nze},Symbol.toStringTag,{value:"Module"})),Fze="layerVertexShader",Bze=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[Fze]=Bze;const kze={name:Fze,shader:Bze},Fyt=Object.freeze(Object.defineProperty({__proto__:null,layerVertexShader:kze},Symbol.toStringTag,{value:"Module"})),Uze="layerPixelShader",zze=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); #ifdef LINEAR baseColor=vec4f(toGammaSpace(baseColor.rgb),baseColor.a); #endif #ifdef ALPHATEST if (baseColor.a<0.4) discard; #endif fragmentOutputs.color=baseColor*uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[Uze]=zze;const Vze={name:Uze,shader:zze},Byt=Object.freeze(Object.defineProperty({__proto__:null,layerPixelShaderWGSL:Vze},Symbol.toStringTag,{value:"Module"})),Gze="layerVertexShader",Wze=`attribute position: vec2f;uniform scale: vec2f;uniform offset: vec2f;uniform textureMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var shiftedPosition: vec2f=input.position*uniforms.scale+uniforms.offset;vertexOutputs.vUV=(uniforms.textureMatrix* vec4f(shiftedPosition*madd+madd,1.0,0.0)).xy;vertexOutputs.position= vec4f(shiftedPosition,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[Gze]=Wze;const Kze={name:Gze,shader:Wze},kyt=Object.freeze(Object.defineProperty({__proto__:null,layerVertexShaderWGSL:Kze},Symbol.toStringTag,{value:"Module"}));class xee{static AddFlare(e,t,i,r,n){return new xee(e,t,i,r,n)}constructor(e,t,i,r,n){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Re(1,1,1),this.texture=r?new xe(r,n.getScene(),!0):null,this._system=n;const a=n.scene.getEngine();n._onShadersLoaded.addOnce(()=>{this._drawWrapper=new Ro(a),this._drawWrapper.effect=a.createEffect("lensFlare",[$.PositionKind],["color","viewportMatrix"],["textureSampler"],"",void 0,void 0,void 0,void 0,n.shaderLanguage)}),n.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}class bv{get scene(){return this._scene}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._shaderLanguage=0,this._vertexBuffers={},this._isEnabled=!0,this._onShadersLoaded=new Ae(void 0,!0),this._shadersLoaded=!1,this._scene=i||Rt.LastCreatedScene,bv._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=a=>i.activeCamera&&a.material&&a.isVisible&&a.isEnabled()&&a.isBlocker&&(a.layerMask&i.activeCamera.layerMask)!=0;const r=i.getEngine(),n=[];n.push(1,1),n.push(-1,1),n.push(-1,-1),n.push(1,-1),this._vertexBuffers[$.PositionKind]=new $(r,n,$.PositionKind,!1,!1,2),this._createIndexBuffer(),this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!bv.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Ue(()=>Promise.resolve().then(()=>Vyt),void 0),Ue(()=>Promise.resolve().then(()=>Gyt),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>Uyt),void 0),Ue(()=>Promise.resolve().then(()=>zyt),void 0)]),this._shadersLoaded=!0,this._onShadersLoaded.notifyObservers()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=D.Project(t,he.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=D.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=this.viewportBorder*2,e.height+=this.viewportBorder*2,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return t.z>0&&!i||t.z<0&&i?(this._positionX>e.x&&this._positionXe.y&&this._positionYi}render(){if(!this._scene.activeCamera||!this._shadersLoaded)return!1;const e=this._scene.getEngine(),i=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(i)||!this._isVisible())return!1;let r,n;this._positionXi.x+i.width-this.borderLimit?r=this._positionX-i.x-i.width+this.borderLimit:r=0,this._positionYi.y+i.height-this.borderLimit?n=this._positionY-i.y-i.height+this.borderLimit:n=0;let a=r>n?r:n;a-=this.viewportBorder,a>this.borderLimit&&(a=this.borderLimit);let o=1-At.Clamp(a/this.borderLimit,0,1);if(o<0)return!1;o>1&&(o=1),this.viewportBorder>0&&(i.x+=this.viewportBorder,i.y+=this.viewportBorder,i.width-=this.viewportBorder*2,i.height-=this.viewportBorder*2,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const l=i.x+i.width/2,c=i.y+i.height/2,u=l-this._positionX,h=c-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let d=0;d{throw vi("LensFlareSystemSceneComponent")};Oa.AddParser(ot.NAME_LENSFLARESYSTEM,(s,e,t,i)=>{if(s.lensFlareSystems!==void 0&&s.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let r=0,n=s.lensFlareSystems.length;r{this.scene.addLensFlareSystem(t)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(i=>{this.scene.removeLensFlareSystem(i),t&&i.dispose()})}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;Me.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Me.EndPerformanceCounter("Lens flares",t.length>0)}}}bv._SceneComponentInitialization=s=>{let e=s._getComponent(ot.NAME_LENSFLARESYSTEM);e||(e=new Hze(s),s._addComponent(e))};const jze="lensFlarePixelShader",Xze=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[jze]=Xze;const Yze={name:jze,shader:Xze},Uyt=Object.freeze(Object.defineProperty({__proto__:null,lensFlarePixelShader:Yze},Symbol.toStringTag,{value:"Module"})),Qze="lensFlareVertexShader",$ze=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[Qze]=$ze;const Zze={name:Qze,shader:$ze},zyt=Object.freeze(Object.defineProperty({__proto__:null,lensFlareVertexShader:Zze},Symbol.toStringTag,{value:"Module"})),qze="lensFlarePixelShader",Jze=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=baseColor*uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[qze]=Jze;const eVe={name:qze,shader:Jze},Vyt=Object.freeze(Object.defineProperty({__proto__:null,lensFlarePixelShaderWGSL:eVe},Symbol.toStringTag,{value:"Module"})),tVe="lensFlareVertexShader",iVe=`attribute position: vec2f;uniform viewportMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position=uniforms.viewportMatrix* vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[tVe]=iVe;const rVe={name:tVe,shader:iVe},Gyt=Object.freeze(Object.defineProperty({__proto__:null,lensFlareVertexShaderWGSL:rVe},Symbol.toStringTag,{value:"Module"}));class pi{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===pi.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===pi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===pi.FILTER_PCF||e===pi.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===pi.FILTER_PCF||e===pi.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===pi.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(pi.FILTER_POISSONSAMPLING);!e&&this.filter!==pi.FILTER_POISSONSAMPLING||(this.filter=e?t:pi.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===pi.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(pi.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==pi.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:pi.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===pi.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(pi.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==pi.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:pi.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===pi.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(pi.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==pi.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:pi.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===pi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(pi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==pi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:pi.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===pi.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(pi.FILTER_PCF);!e&&this.filter!==pi.FILTER_PCF||(this.filter=e?t:pi.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===pi.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(pi.FILTER_PCSS);!e&&this.filter!==pi.FILTER_PCSS||(this.filter=e?t:pi.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return pi.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(const i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(const r of e.getChildren())this.removeShadowCaster(r);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,n,a=!1){this.onBeforeShadowMapRenderObservable=new Ae,this.onAfterShadowMapRenderObservable=new Ae,this.onBeforeShadowMapRenderMeshObservable=new Ae,this.onAfterShadowMapRenderMeshObservable=new Ae,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=pi.FILTER_NONE,this._filteringQuality=pi.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=D.Zero(),this._viewMatrix=he.Zero(),this._projectionMatrix=he.Zero(),this._transformMatrix=he.Zero(),this._cachedPosition=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=he.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=r??null,this._useRedTextureType=!!n,this._initShaderSourceAsync(a);let o=t._shadowGenerators;o||(o=t._shadowGenerators=new Map),o.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),pi._SceneComponentInitialization(this._scene);const l=this._scene.getEngine().getCaps();i?l.textureFloatRender&&l.textureFloatLinearFiltering?this._textureType=1:l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering?this._textureType=2:l.textureFloatRender&&l.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new Rs(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new Rs(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=xe.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=xe.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(xe.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(r,n,a,o)=>this._renderForShadowMap(r,n,a,o),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var r;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(r=e._debugPushGroup)==null||r.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(r=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=r,this._filter===pi.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var n,a;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===pi.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(n=e._debugPopGroup)==null||n.call(e,1);return}const r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),(a=e._debugPopGroup)==null||a.call(e,1))});const t=new Ze(0,0,0,0),i=new Ze(1,1,1,1);this._shadowMap.onClearObservable.add(r=>{this._filter===pi.FILTER_PCF?r.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.clear(t,!0,!0,!1):r.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(r=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=r.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let r=Wl.MIN_RENDERINGGROUPS;rPromise.resolve().then(()=>nxt),void 0),Ue(()=>Promise.resolve().then(()=>hxt),void 0),Ue(()=>Promise.resolve().then(()=>dxt),void 0),Ue(()=>Promise.resolve().then(()=>fxt),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>yxt),void 0),Ue(()=>Promise.resolve().then(()=>Bxt),void 0),Ue(()=>Promise.resolve().then(()=>kxt),void 0),Ue(()=>Promise.resolve().then(()=>Uxt),void 0)]),this._shadersLoaded=!0}_initializeBlurRTTAndPostProcesses(){const e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new Rs(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=xe.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=xe.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(xe.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new Ho(this._light.name+"KernelBlurX",new we(1,0),this.blurKernel,1,null,xe.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(i=>{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new Ho(this._light.name+"KernelBlurY",new we(0,1),this.blurKernel,1,null,xe.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Ft(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,xe.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let n;if(r.length)for(n=0;n{r!==i&&!x?(i.getMeshUniformBuffer().bindToEffect(_,"Mesh"),i.transferToEffect(A)):(r.getMeshUniformBuffer().bindToEffect(_,"Mesh"),r.transferToEffect(x?A:v))}),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(_),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===pi.FILTER_NONE||this.filter===pi.FILTER_PCSS?this._shadowMap.updateSamplingMode(xe.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(xe.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},r=this.getShadowMap();if(!r){e&&e(this);return}const n=r.renderList;if(!n){e&&e(this);return}const a=[];for(const c of n)a.push(...c.subMeshes);if(a.length===0){e&&e(this);return}let o=0;const l=()=>{var c;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(a[o],i.useInstances,((c=a[o].getMaterial())==null?void 0:c.needAlphaBlendingForMesh(a[o].getMesh()))??!1);)if(o++,o>=a.length){e&&e(this);return}setTimeout(l,16)}};l()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const n=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&n.isVerticesDataPresent($.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Zi.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){if(!this._shadersLoaded)return!1;const r=e.getMaterial(),n=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const o=e._getDrawWrapper(void 0,!0);let l=o.effect,c=o.defines;const u=[$.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent($.NormalKind)&&(u.push($.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));const d=r.needAlphaTesting();if((d||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const y=r.alphaCutOff??pi.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),d&&a.push(`#define ALPHATESTVALUE ${y}${y%1===0?".":""}`),h.isVerticesDataPresent($.UVKind)&&(u.push($.UVKind),a.push("#define UV1")),h.isVerticesDataPresent($.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(u.push($.UV2Kind),a.push("#define UV2"))}const f=new oa;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){u.push($.MatricesIndicesKind),u.push($.MatricesWeightsKind),h.numBoneInfluencers>4&&(u.push($.MatricesIndicesExtraKind),u.push($.MatricesWeightsExtraKind));const y=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,h),y.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(y.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const p=h.morphTargetManager;let m=0;if(p&&(m=p.numMaxInfluencers||p.numInfluencers,m>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+m),p.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),rT(u,h,m))),t3(r,this._scene,a),t&&(a.push("#define INSTANCES"),A_(u),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const y of this.customShaderOptions.defines)a.indexOf(y)===-1&&a.push(y);const g=h.bakedVertexAnimationManager;t&&g&&g.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.push("bakedVertexAnimationSettingsInstanced"));const _=a.join(` `);if(c!==_){c=_;let y="shadowMap";const v=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],x=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],A=["Scene","Mesh"];if(fo(v),this.customShaderOptions){if(y=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const C of this.customShaderOptions.attributes)u.indexOf(C)===-1&&u.push(C);if(this.customShaderOptions.uniforms)for(const C of this.customShaderOptions.uniforms)v.indexOf(C)===-1&&v.push(C);if(this.customShaderOptions.samplers)for(const C of this.customShaderOptions.samplers)x.indexOf(C)===-1&&x.push(C)}const b=this._scene.getEngine();l=b.createEffect(y,{attributes:u,uniformsNames:v,uniformBuffersNames:A,samplers:x,defines:_,fallbacks:f,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._shaderLanguage},b),o.setEffect(l,c)}if(!l.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,r=this._light;!i.shadowsEnabled||!r.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===pi.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===pi.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===pi.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===pi.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const a=this.getShadowMap();if(!a)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const o=this.getShadowMapForRendering();this._filter===pi.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===pi.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,o),t.setTexture("depthTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),D.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(D.Dot(this._lightDirection,D.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),he.LookAtLHToRef(t,t.add(this._lightDirection),D.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const r=i.renderList;r&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,r)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();t.done!==!0;t=e.next()){const[i,r]=t.value;r===this&&this._light._shadowGenerators.delete(i)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var i;const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=(i=this._camera)==null?void 0:i.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let r=0;r{throw vi("ShadowGeneratorSceneComponent")};const sVe="packingFunctions",nVe=`vec4 pack(float depth) {const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} float unpack(vec4 color) {const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;de.IncludesShadersStore[sVe]=nVe;const aVe={name:sVe,shader:nVe},Wyt=Object.freeze(Object.defineProperty({__proto__:null,packingFunctions:aVe},Symbol.toStringTag,{value:"Module"})),oVe="depthPixelShader",lVe=`#ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include varying float vDepthMetric; #ifdef PACKED #include #endif #ifdef STORE_CAMERASPACE_Z varying vec4 vViewPos; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif #ifdef STORE_CAMERASPACE_Z #ifdef PACKED gl_FragColor=pack(vViewPos.z); #else gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); #endif #else #ifdef NONLINEARDEPTH #ifdef PACKED gl_FragColor=pack(gl_FragCoord.z); #else gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); #endif #else #ifdef PACKED gl_FragColor=pack(vDepthMetric); #else gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); #endif #endif #endif }`;de.ShadersStore[oVe]=lVe;const cVe={name:oVe,shader:lVe},Kyt=Object.freeze(Object.defineProperty({__proto__:null,depthPixelShader:cVe},Symbol.toStringTag,{value:"Module"})),Hyt="pointCloudVertexDeclaration",jyt=`#ifdef POINTSIZE uniform float pointSize; #endif `;de.IncludesShadersStore[Hyt]=jyt;const Xyt="pointCloudVertex",Yyt=`#if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif `;de.IncludesShadersStore[Xyt]=Yyt;const uVe="depthVertexShader",hVe=`attribute vec3 position; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform mat4 viewProjection;uniform vec2 depthValues; #if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #ifdef STORE_CAMERASPACE_Z uniform mat4 view;varying vec4 vViewPos; #endif #include varying float vDepthMetric; #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #include gl_Position=viewProjection*worldPos; #ifdef STORE_CAMERASPACE_Z vViewPos=view*worldPos; #else #ifdef USE_REVERSE_DEPTHBUFFER vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); #else vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); #endif #endif #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include } `;de.ShadersStore[uVe]=hVe;const dVe={name:uVe,shader:hVe},Qyt=Object.freeze(Object.defineProperty({__proto__:null,depthVertexShader:dVe},Symbol.toStringTag,{value:"Module"}));class u_{get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,n=xe.TRILINEAR_SAMPLINGMODE,a=!1,o){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=t===0,this.isPacked?this.clearColor=new Ze(1,1,1,1):this.clearColor=new Ze(a?1e8:1,0,0,1),this._initShaderSourceAsync(),u_._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,n!==xe.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(n=xe.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(n=xe.NEAREST_SAMPLINGMODE));const c=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new Rs(o??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,n,void 0,void 0,void 0,c),this._depthMap.wrapU=xe.CLAMP_ADDRESSMODE,this._depthMap.wrapV=xe.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(h=>{h.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var h;(h=l._debugPushGroup)==null||h.call(l,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var h;(h=l._debugPopGroup)==null||h.call(l,1)}),this._depthMap.customIsReadyFunction=(h,d,f)=>{if((f||d===0)&&h.subMeshes)for(let p=0;p{var C;const d=h.getRenderingMesh(),f=h.getEffectiveMesh(),p=this._scene,m=p.getEngine(),g=h.getMaterial();if(f._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!g||f.infiniteDistance||g.disableDepthWrite||h.verticesCount===0||h._renderId===p.getRenderId())return;const _=f._getWorldMatrixDeterminant()<0;let y=g._getEffectiveOrientation(d);_&&(y=y===0?1:0);const v=y===0;m.setState(g.backFaceCulling,0,!1,v,this.reverseCulling?!g.cullBackFaces:g.cullBackFaces);const x=d._getInstancesRenderList(h._id,!!h.getReplacementMesh());if(x.mustReturn)return;const A=m.getCaps().instancedArrays&&(x.visibleInstances[h._id]!==null&&x.visibleInstances[h._id]!==void 0||d.hasThinInstances),b=this._camera||p.activeCamera;if(this.isReady(h,A)&&b){h._renderId=p.getRenderId();const T=(C=f._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:C[m.currentRenderPassId];let w=h._getDrawWrapper();!w&&T&&(w=T._getDrawWrapper());const P=b.mode===Nt.ORTHOGRAPHIC_CAMERA;if(!w)return;const M=w.effect;m.enableEffect(w),A||d._bind(h,M,g.fillMode),T?T.bindForSubMesh(f.getWorldMatrix(),f,h):(M.setMatrix("viewProjection",p.getTransformMatrix()),M.setMatrix("world",f.getWorldMatrix()),this._storeCameraSpaceZ&&M.setMatrix("view",p.getViewMatrix()));let R,I;if(P?(R=!m.useReverseDepthBuffer&&m.isNDCHalfZRange?0:1,I=m.useReverseDepthBuffer&&m.isNDCHalfZRange?0:1):(R=m.useReverseDepthBuffer&&m.isNDCHalfZRange?b.minZ:m.isNDCHalfZRange?0:b.minZ,I=m.useReverseDepthBuffer&&m.isNDCHalfZRange?0:b.maxZ),M.setFloat2("depthValues",R,R+I),!T){if(g.needAlphaTesting()){const L=g.getAlphaTestTexture();L&&(M.setTexture("diffuseSampler",L),M.setMatrix("diffuseMatrix",L.getTextureMatrix()))}if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){const L=d.skeleton;if(L.isUsingTextureForMatrices){const k=L.getTransformMatrixTexture(d);if(!k)return;M.setTexture("boneSampler",k),M.setFloat("boneTextureWidth",4*(L.bones.length+1))}else M.setMatrices("mBones",L.getTransformMatrices(d))}Xa(M,g,p),I0(d,M),d.morphTargetManager&&d.morphTargetManager.isUsingTextureForTargets&&d.morphTargetManager._bind(M),g.pointsCloud&&M.setFloat("pointSize",g.pointSize)}d._processRendering(f,h,M,g.fillMode,x,A,(L,k)=>M.setMatrix("world",k))}};this._depthMap.customRenderFunction=(h,d,f,p)=>{let m;if(p.length)for(m=0;mPromise.resolve().then(()=>x5t),void 0),Ue(()=>Promise.resolve().then(()=>y5t),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>Qyt),void 0),Ue(()=>Promise.resolve().then(()=>Kyt),void 0)]),this._shadersLoaded=!0}isReady(e,t){var m;if(!this._shadersLoaded)return!1;const i=this._scene.getEngine(),r=e.getMesh(),n=r.getScene(),a=(m=r._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:m[i.currentRenderPassId];if(a)return a.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;const l=[],c=[$.PositionKind];if(o&&o.needAlphaTesting()&&o.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),r.isVerticesDataPresent($.UVKind)&&(c.push($.UVKind),l.push("#define UV1")),r.isVerticesDataPresent($.UV2Kind)&&(c.push($.UV2Kind),l.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders){c.push($.MatricesIndicesKind),c.push($.MatricesWeightsKind),r.numBoneInfluencers>4&&(c.push($.MatricesIndicesExtraKind),c.push($.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),l.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0));const g=e.getRenderingMesh().skeleton;g!=null&&g.isUsingTextureForMatrices&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const u=r.morphTargetManager;let h=0;u&&(h=u.numMaxInfluencers||u.numInfluencers,h>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+h),u.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),rT(c,r,h))),o.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),A_(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),t3(o,n,l);const d=e._getDrawWrapper(void 0,!0),f=d.defines,p=l.join(` `);if(f!==p){const g=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];fo(g),d.setEffect(i.createEffect("depth",c,g,["diffuseSampler","morphTargets","boneSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h},this._shaderLanguage),p)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}u_.ForceGLSL=!1;u_._SceneComponentInitialization=s=>{throw vi("DepthRendererSceneComponent")};const $yt="minmaxReduxPixelShader",Zyt=`varying vec2 vUV;uniform sampler2D textureSampler; #if defined(INITIAL) uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); #ifdef DEPTH_REDUX float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); #else float maxz=max(max(max(f1,f2),f3),f4); #endif glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(MAIN) uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(ONEBEFORELAST) uniform ivec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(LAST) void main(void) {glFragColor=vec4(0.);if (true) { discard;}} #endif `;de.ShadersStore[$yt]=Zyt;class fVe{constructor(e){this.onAfterReductionPerformed=new Ae,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Bk(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;const n=this._camera.getScene(),a=new Ft("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,n.getEngine(),!1,"#define INITIAL"+(t?` #define DEPTH_REDUX`:""),i,void 0,void 0,void 0,7);a.autoClear=!1,a.forceFullscreenViewport=r;let o=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();a.onApply=((u,h)=>d=>{d.setTexture("sourceTexture",this._sourceTexture),d.setFloat2("texSize",u,h)})(o,l),this._reductionSteps.push(a);let c=1;for(;o>1||l>1;){o=Math.max(Math.round(o/2),1),l=Math.max(Math.round(l/2),1);const u=new Ft("Reduction phase "+c,"minmaxRedux",["texSize"],null,{width:o,height:l},null,1,n.getEngine(),!1,"#define "+(o==1&&l==1?"LAST":o==1||l==1?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(u.autoClear=!1,u.forceFullscreenViewport=r,u.onApply=((h,d)=>f=>{h==1||d==1?f.setInt2("texSize",h,d):f.setFloat2("texSize",h,d)})(o,l),this._reductionSteps.push(u),c++,o==1&&l==1){const h=(d,f,p)=>{const m=new Float32Array(4*d*f),g={min:0,max:0};return()=>{n.getEngine()._readTexturePixels(p.inputTexture.texture,d,f,-1,0,m,!1),g.min=m[0],g.max=m[1],this.onAfterReductionPerformed.notifyObservers(g)}};u.onAfterRenderObservable.add(h(o,l,u))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var t,i;const e=this._camera.getScene().getEngine();(t=e._debugPushGroup)==null||t.call(e,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),(i=e._debugPopGroup)==null||i.call(e,1)}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let t=0;tthis._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let i=0;it&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return Cl.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let r=i.min,n=i.max;r>=n&&(r=0,n=1),(r!=this._minDistance||n!=this._maxDistance)&&this.setMinMaxDistance(r,n)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t;return((t=(e=this._depthReducer)==null?void 0:e.depthRenderer)==null?void 0:t.getDepthMap().refreshRate)??-1}set autoCalcDepthBoundsRefreshRate(e){var t;(t=this._depthReducer)!=null&&t.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,n=this._minDistance,a=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+n*r,l=t+a*r,c=l-o,u=l/o;for(let h=0;h{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===pi.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(t=e._debugPushGroup)==null||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==pi.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const n=this._getCamera();n&&this._shadowMaxZ<=(n.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const a=this.getShadowMap();if(!a)return;const o=a.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===pi.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===pi.FILTER_PCSS){for(let l=0;lnew Cl(r,n,void 0,a));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Cl._FrustumCornersNDCSpace=[new D(-1,1,-1),new D(1,1,-1),new D(1,-1,-1),new D(-1,-1,-1),new D(-1,1,1),new D(1,1,1),new D(1,-1,1),new D(-1,-1,1)];Cl.CLASSNAME="CascadedShadowGenerator";Cl.DEFAULT_CASCADES_COUNT=4;Cl.MIN_CASCADES_COUNT=2;Cl.MAX_CASCADES_COUNT=4;Cl._SceneComponentInitialization=s=>{throw vi("ShadowGeneratorSceneComponent")};Oa.AddParser(ot.NAME_SHADOWGENERATOR,(s,e)=>{if(s.shadowGenerators!==void 0&&s.shadowGenerators!==null)for(let t=0,i=s.shadowGenerators.length;t{let e=s._getComponent(ot.NAME_SHADOWGENERATOR);e||(e=new mVe(s),s._addComponent(e))};const gVe="packingFunctions",_Ve=`fn pack(depth: f32)->vec4f {const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} fn unpack(color: vec4f)->f32 {const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;de.IncludesShadersStoreWGSL[gVe]=_Ve;const vVe={name:gVe,shader:_Ve},Jyt=Object.freeze(Object.defineProperty({__proto__:null,packingFunctionsWGSL:vVe},Symbol.toStringTag,{value:"Module"})),ext="bayerDitherFunctions",txt=`fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));} fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); var P2: vec2f=floor(0.5*((_P)%(4.0))); return 4.0*bayerDither2(P1)+bayerDither2(P2);} fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); var P2: vec2f=floor(0.5 *((_P)%(4.0))); var P4: vec2f=floor(0.25*((_P)%(8.0))); return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} `;de.IncludesShadersStoreWGSL[ext]=txt;const ixt="shadowMapFragmentExtraDeclaration",rxt=`#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 #include uniform softTransparentShadowSM: vec2f; #endif varying vDepthMetricSM: f32; #if SM_USEDISTANCE==1 uniform lightDataSM: vec3f;varying vPositionWSM: vec3f; #endif uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying zSM: f32; #endif `;de.IncludesShadersStoreWGSL[ixt]=rxt;const yVe="shadowMapFragment",xVe=`var depthSM: f32=fragmentInputs.vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #else #ifdef USE_REVERSE_DEPTHBUFFER depthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #else depthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #endif #ifdef USE_REVERSE_DEPTHBUFFER fragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0); #else fragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0); #endif #elif SM_USEDISTANCE==1 depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #if SM_ESM==1 depthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.); #endif #if SM_FLOAT==1 fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0); #else fragmentOutputs.color=pack(depthSM); #endif `;de.IncludesShadersStoreWGSL[yVe]=xVe;const AVe={name:yVe,shader:xVe},sxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragmentWGSL:AVe},Symbol.toStringTag,{value:"Module"})),bVe="shadowMapPixelShader",CVe=`#include #ifdef ALPHATEXTURE varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include #ifdef ALPHATEXTURE var opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a; #if SM_SOFTTRANSPARENTSHADOW==1 if (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;} #endif #ifdef ALPHATESTVALUE if (alphaFromAlphaTexture=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;} #else if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;} #endif #endif #include }`;de.ShadersStoreWGSL[bVe]=CVe;const SVe={name:bVe,shader:CVe},nxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapPixelShaderWGSL:SVe},Symbol.toStringTag,{value:"Module"})),axt="shadowMapVertexExtraDeclaration",oxt=`#if SM_NORMALBIAS==1 uniform lightDataSM: vec3f; #endif uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32; #if SM_USEDISTANCE==1 varying vPositionWSM: vec3f; #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying zSM: f32; #endif `;de.IncludesShadersStoreWGSL[axt]=oxt;const lxt="shadowMapVertexNormalBias",cxt=`#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz); #else var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM); #endif var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w); #endif `;de.IncludesShadersStoreWGSL[lxt]=cxt;const EVe="shadowMapVertexMetric",TVe=`#if SM_USEDISTANCE==1 vertexOutputs.vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 #ifdef IS_NDC_HALF_ZRANGE #define BIASFACTOR 0.5 #else #define BIASFACTOR 1.0 #endif #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR; #else vertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR; #endif #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 vertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0; #elif SM_USEDISTANCE==0 #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #else vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #endif `;de.IncludesShadersStoreWGSL[EVe]=TVe;const MVe={name:EVe,shader:TVe},uxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexMetricWGSL:MVe},Symbol.toStringTag,{value:"Module"})),RVe="shadowMapVertexShader",IVe=`attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #ifdef INSTANCES attribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f; #endif #include #include #include #ifdef ALPHATEXTURE varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #include #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #ifdef NORMAL var normalUpdated: vec3f=input.normal; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); #ifdef NORMAL var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); #if defined(INSTANCES) && defined(THIN_INSTANCES) var vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif var vNormalW: vec3f=normalize(normWorldSM*normalUpdated); #endif #endif #include vertexOutputs.position=scene.viewProjection*worldPos; #include #ifdef ALPHATEXTURE #ifdef UV1 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef UV2 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #endif #include }`;de.ShadersStoreWGSL[RVe]=IVe;const PVe={name:RVe,shader:IVe},hxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexShaderWGSL:PVe},Symbol.toStringTag,{value:"Module"})),wVe="depthBoxBlurPixelShader",DVe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}} fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`;de.ShadersStoreWGSL[wVe]=DVe;const LVe={name:wVe,shader:DVe},dxt=Object.freeze(Object.defineProperty({__proto__:null,depthBoxBlurPixelShaderWGSL:LVe},Symbol.toStringTag,{value:"Module"})),OVe="shadowMapFragmentSoftTransparentShadow",NVe=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;} #endif `;de.IncludesShadersStoreWGSL[OVe]=NVe;const FVe={name:OVe,shader:NVe},fxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragmentSoftTransparentShadowWGSL:FVe},Symbol.toStringTag,{value:"Module"})),pxt="bayerDitherFunctions",mxt=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5*mod(_P,4.0)); return 4.0*bayerDither2(P1)+bayerDither2(P2);} float bayerDither8(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*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} `;de.IncludesShadersStore[pxt]=mxt;const gxt="shadowMapFragmentExtraDeclaration",_xt=`#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 #include uniform vec2 softTransparentShadowSM; #endif varying float vDepthMetricSM; #if SM_USEDISTANCE==1 uniform vec3 lightDataSM;varying vec3 vPositionWSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif `;de.IncludesShadersStore[gxt]=_xt;const BVe="shadowMapFragment",kVe=`float depthSM=vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else #ifdef USE_REVERSE_DEPTHBUFFER depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif #ifdef USE_REVERSE_DEPTHBUFFER gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); #else gl_FragDepth=clamp(depthSM,0.0,1.0); #endif #elif SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #if SM_ESM==1 depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); #endif #if SM_FLOAT==1 gl_FragColor=vec4(depthSM,1.0,1.0,1.0); #else gl_FragColor=pack(depthSM); #endif return;`;de.IncludesShadersStore[BVe]=kVe;const UVe={name:BVe,shader:kVe},vxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragment:UVe},Symbol.toStringTag,{value:"Module"})),zVe="shadowMapPixelShader",VVe=`#include #ifdef ALPHATEXTURE varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include #ifdef ALPHATEXTURE vec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a; #if SM_SOFTTRANSPARENTSHADOW==1 if (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;} #endif #ifdef ALPHATESTVALUE if (alphaFromAlphaTexture=softTransparentShadowSM.x*alphaFromAlphaTexture) discard; #else if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard; #endif #endif #include }`;de.ShadersStore[zVe]=VVe;const GVe={name:zVe,shader:VVe},yxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapPixelShader:GVe},Symbol.toStringTag,{value:"Module"})),xxt="sceneVertexDeclaration",Axt=`uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; `;de.IncludesShadersStore[xxt]=Axt;const bxt="meshVertexDeclaration",Cxt=`uniform mat4 world;uniform float visibility; `;de.IncludesShadersStore[bxt]=Cxt;const Sxt="shadowMapVertexDeclaration",Ext=`#include #include `;de.IncludesShadersStore[Sxt]=Ext;const Txt="sceneUboDeclaration",Mxt=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif mat4 view;mat4 projection;vec4 vEyePosition;}; `;de.IncludesShadersStore[Txt]=Mxt;const Rxt="meshUboDeclaration",Ixt=`#ifdef WEBGL2 uniform mat4 world;uniform float visibility; #else layout(std140,column_major) uniform;uniform Mesh {mat4 world;float visibility;}; #endif #define WORLD_UBO `;de.IncludesShadersStore[Rxt]=Ixt;const Pxt="shadowMapUboDeclaration",wxt=`layout(std140,column_major) uniform; #include #include `;de.IncludesShadersStore[Pxt]=wxt;const Dxt="shadowMapVertexExtraDeclaration",Lxt=`#if SM_NORMALBIAS==1 uniform vec3 lightDataSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; #if SM_USEDISTANCE==1 varying vec3 vPositionWSM; #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif `;de.IncludesShadersStore[Dxt]=Lxt;const Oxt="shadowMapVertexNormalBias",Nxt=`#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 vec3 worldLightDirSM=normalize(-lightDataSM.xyz); #else vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); #endif float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; #endif `;de.IncludesShadersStore[Oxt]=Nxt;const WVe="shadowMapVertexMetric",KVe=`#if SM_USEDISTANCE==1 vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 #ifdef IS_NDC_HALF_ZRANGE #define BIASFACTOR 0.5 #else #define BIASFACTOR 1.0 #endif #ifdef USE_REVERSE_DEPTHBUFFER gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; #else gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; #endif #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 zSM=gl_Position.z;gl_Position.z=0.0; #elif SM_USEDISTANCE==0 #ifdef USE_REVERSE_DEPTHBUFFER vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif `;de.IncludesShadersStore[WVe]=KVe;const HVe={name:WVe,shader:KVe},Fxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexMetric:HVe},Symbol.toStringTag,{value:"Module"})),jVe="shadowMapVertexShader",XVe=`attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #endif #include #include<__decl__shadowMapVertex> #ifdef ALPHATEXTURE varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #include #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef NORMAL vec3 normalUpdated=normal; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef NORMAL mat3 normWorldSM=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif vec3 vNormalW=normalize(normWorldSM*normalUpdated); #endif #endif #include gl_Position=viewProjection*worldPos; #include #ifdef ALPHATEXTURE #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include }`;de.ShadersStore[jVe]=XVe;const YVe={name:jVe,shader:XVe},Bxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexShader:YVe},Symbol.toStringTag,{value:"Module"})),QVe="depthBoxBlurPixelShader",$Ve=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) for (int y=-OFFSET; y<=OFFSET; y++) colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;de.ShadersStore[QVe]=$Ve;const ZVe={name:QVe,shader:$Ve},kxt=Object.freeze(Object.defineProperty({__proto__:null,depthBoxBlurPixelShader:ZVe},Symbol.toStringTag,{value:"Module"})),qVe="shadowMapFragmentSoftTransparentShadow",JVe=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard; #endif `;de.IncludesShadersStore[qVe]=JVe;const eGe={name:qVe,shader:JVe},Uxt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragmentSoftTransparentShadow:eGe},Symbol.toStringTag,{value:"Module"}));ns.AddNodeConstructor("Light_Type_0",(s,e)=>()=>new ig(s,D.Zero(),e));class ig extends Gx{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Zi.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new D(1,0,0);case 1:return new D(-1,0,0);case 2:return new D(0,-1,0);case 3:return new D(0,1,0);case 4:return new D(0,0,1);case 5:return new D(0,0,-1)}return D.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;const n=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,a=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;he.PerspectiveFovLHToRef(this.shadowAngle,1,o?a:n,o?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}F([X()],ig.prototype,"shadowAngle",null);ve("BABYLON.PointLight",ig);class fv{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const r=this._renderingCanvas.getBoundingClientRect(),n=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position=n==="fixed"?"fixed":"absolute",this._loadingDiv.style.left=r.left+"px",this._loadingDiv.style.top=r.top+"px",this._loadingDiv.style.width=r.width+"px",this._loadingDiv.style.height=r.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";const e=`@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);} 100% { -webkit-transform: rotate(360deg);} } @keyframes spin1 { 0% { transform: rotate(0deg);} 100% { transform: rotate(360deg);} }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);const t=!!window.SVGSVGElement,i=new Image;fv.DefaultLogoUrl?i.src=fv.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";const n=new Image;if(fv.DefaultSpinnerUrl?n.src=fv.DefaultSpinnerUrl:n.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",n.style.animation="spin1 0.75s infinite linear",n.style.webkitAnimation="spin1 0.75s infinite linear",n.style.transformOrigin="50% 50%",n.style.webkitTransformOrigin="50% 50%",!t){const a={w:16,h:18.5},o={w:30,h:30};i.style.width=`${a.w}vh`,i.style.height=`${a.h}vh`,i.style.left=`calc(50% - ${a.w/2}vh)`,i.style.top=`calc(50% - ${a.h/2}vh)`,n.style.width=`${o.w}vh`,n.style.height=`${o.h}vh`,n.style.left=`calc(50% - ${o.w/2}vh)`,n.style.top=`calc(50% - ${o.h/2}vh)`}r.appendChild(n),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){if(!this._loadingDiv)return;const e=()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",e)}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}fv.DefaultLogoUrl="";fv.DefaultSpinnerUrl="";Ge.DefaultLoadingScreenFactory=s=>new fv(s);class r3{static ConvertPanoramaToCubemap(e,t,i,r,n=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";const a=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,n),o=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,n),l=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,n),c=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,n),u=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,n),h=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,n);return{front:a,back:o,left:l,right:c,up:u,down:h,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,n,a=!1){const o=new ArrayBuffer(e*e*4*3),l=new Float32Array(o),c=a?Math.max(1,Math.round(r/4/e)):1,u=1/c,h=u*u,d=t[1].subtract(t[0]).scale(u/e),f=t[3].subtract(t[2]).scale(u/e),p=1/e;let m=0;for(let g=0;gMath.PI;)n-=2*Math.PI;let o=n/Math.PI;const l=a/Math.PI;o=o*.5+.5;let c=Math.round(o*i);c<0?c=0:c>=i&&(c=i-1);let u=Math.round(l*r);u<0?u=0:u>=r&&(u=r-1);const h=r-u-1,d=t[h*i*3+c*3+0],f=t[h*i*3+c*3+1],p=t[h*i*3+c*3+2];return{r:d,g:f,b:p}}}r3.FACE_LEFT=[new D(-1,-1,-1),new D(1,-1,-1),new D(-1,1,-1),new D(1,1,-1)];r3.FACE_RIGHT=[new D(1,-1,1),new D(-1,-1,1),new D(1,1,1),new D(-1,1,1)];r3.FACE_FRONT=[new D(1,-1,-1),new D(1,-1,1),new D(1,1,-1),new D(1,1,1)];r3.FACE_BACK=[new D(-1,-1,1),new D(-1,-1,-1),new D(-1,1,1),new D(-1,1,-1)];r3.FACE_DOWN=[new D(1,1,-1),new D(1,1,1),new D(-1,1,-1),new D(-1,1,1)];r3.FACE_UP=[new D(-1,-1,-1),new D(-1,-1,1),new D(1,-1,-1),new D(1,-1,1)];function zxt(s,e){return e>1023?s*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?s*Math.pow(2,-1074)*Math.pow(2,e+1074):s*Math.pow(2,e)}function tGe(s,e,t,i,r,n){r>0?(r=zxt(1,r-136),s[n+0]=e*r,s[n+1]=t*r,s[n+2]=i*r):(s[n+0]=0,s[n+1]=0,s[n+2]=0)}function Kne(s,e){let t="",i="";for(let r=e;r32767)throw"HDR Bad header format, unsupported size";return a+=i.length+1,{height:e,width:t,dataPosition:a}}function iGe(s,e,t=!1){const i=new Uint8Array(s),r=G1e(i),n=W1e(i,r);return r3.ConvertPanoramaToCubemap(n,r.width,r.height,e,t)}function W1e(s,e){return Vxt(s,e)}function Vxt(s,e){let t=e.height;const i=e.width;let r,n,a,o,l,c=e.dataPosition,u=0,h=0,d=0;const f=new ArrayBuffer(i*4),p=new Uint8Array(f),m=new ArrayBuffer(e.width*e.height*4*3),g=new Float32Array(m);for(;t>0;){if(r=s[c++],n=s[c++],a=s[c++],o=s[c++],r!=2||n!=2||a&128||e.width<8||e.width>32767)return Gxt(s,e);if((a<<8|o)!=i)throw"HDR Bad header format, wrong scan line width";for(u=0,d=0;d<4;d++)for(h=(d+1)*i;u128){if(l=r-128,l==0||l>h-u)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)p[u++]=n}else{if(l=r,l==0||l>h-u)throw"HDR Bad Format, bad scanline data (non-run)";if(p[u++]=n,--l>0)for(let _=0;_0;){for(l=0;l0 #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) float radicalInverse_VdC(uint bits) {bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } vec2 hammersley(uint i,uint N) {return vec2(float(i)/float(N),radicalInverse_VdC(i));} #else float vanDerCorpus(int n,int base) {float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) {if(n>0) {denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} return result;} vec2 hammersley(int i,int N) {return vec2(float(i)/float(N),vanDerCorpus(i,2));} #endif float log4(float x) {return log2(x)/2.;} const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; #define inline vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) {vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) for(uint i=0u; i0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif result+=c;}} result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} #define inline vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) {vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; if (alphaG==0.) { #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif result+=c*NoL;}} result=result/weight;return result;}} #endif #endif `;de.IncludesShadersStore[$xt]=Zxt;const qxt="hdrFilteringPixelShader",Jxt=`#include #include #include #include uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;de.ShadersStore[qxt]=Jxt;class K1e{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);const i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){const t=e.getSize().width,i=At.ILog2(t)+1,r=this._effectWrapper.effect,n=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();const a=e.getInternalTexture();a&&this._engine.updateTextureSamplingMode(3,a,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);const o=[[new D(0,0,-1),new D(0,-1,0),new D(1,0,0)],[new D(0,0,1),new D(0,-1,0),new D(-1,0,0)],[new D(1,0,0),new D(0,0,1),new D(0,1,0)],[new D(1,0,0),new D(0,0,-1),new D(0,-1,0)],[new D(1,0,0),new D(0,-1,0),new D(0,0,1)],[new D(-1,0,0),new D(0,-1,0),new D(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let u=0;u<6;u++){r.setVector3("up",o[u][0]),r.setVector3("right",o[u][1]),r.setVector3("front",o[u][2]);for(let h=0;h{this._effectRenderer=new Pz(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(fe.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class e_ extends $r{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(he.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,n=!0,a=!1,o=!1,l=null,c=null,u=!1){var h;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=D.Zero(),this.onLoadObservable=new Ae,e&&(this._coordinatesMode=xe.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=he.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),l&&l()},this._onError=c,this.gammaSpace=a,this._noMipmap=r,this._size=i,this._supersample=u,this._generateHarmonics=n,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Me.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(h=this.getScene())!=null&&h.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2);const r=n=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const a=iGe(n,this._size,this._supersample);if(this._generateHarmonics){const u=oT.ConvertCubeMapToSphericalPolynomial(a);this.sphericalPolynomial=u}const o=[];let l=null,c=null;for(let u=0;u<6;u++){i===2?c=new Uint16Array(this._size*this._size*3):i===0&&(l=new Uint8Array(this._size*this._size*3));const h=a[e_._FacesMapping[u]];if(this.gammaSpace||c||l){for(let d=0;d255){const _=255/g;f*=_,p*=_,m*=_}l[d*3+0]=f,l[d*3+1]=p,l[d*3+2]=m}}c?o.push(c):l?o.push(l):o.push(h)}return o};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const n=this._onLoad,a=new K1e(e);this._onLoad=()=>{a.prefilter(this,n)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,r,null,this._onLoad,this._onError)}clone(){const e=new e_(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&((t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.getActiveTextures().indexOf(this)!==-1))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&(r=new e_(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),r.name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=D.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=D.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}e_._FacesMapping=["right","left","up","down","front","back"];ve("BABYLON.HDRCubeTexture",e_);class rx{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(t===0||e===0)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new Ae,this._onDataLayoutChanged=new Ae,this._animationPropertiesOverride=null,this._scene=i||Rt.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=qe.Clone(()=>new rx(this.name,this.influence,this._scene),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),this.id!=null&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),qe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new rx(e.name,e.influence);if(i.setPositions(e.positions),e.id!=null&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let r=0;r0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new no(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=Rt.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const t=this._scene.getEngine().getCaps();this._canUseTextureForTargets=t.canUseGLVertexID&&t.textureFloat&&t.maxVertexTextureImageUnits>0&&t.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){var e;return f0.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!((e=this._scene)!=null&&e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(t=>{this._syncActiveTargets(t)})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(()=>{this._syncActiveTargets(!0)})),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new f0(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const r of this._targets){if(i++,r.influence===0&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=f0.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(r),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=r.influence,this._supportsNormals=this._supportsNormals&&r.hasNormals,this._supportsTangents=this._supportsTangents&&r.hasTangents,this._supportsUVs=this._supportsUVs&&r.hasUVs;const n=r.getPositions();if(n){const a=n.length/3;if(this._vertexCount===0)this._vertexCount=a;else if(this._vertexCount!==a){fe.Error("Incompatible target. Targets must all have the same vertices count.");return}}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),(!this._influences||this._influences.length!==t)&&(this._influences=new Float32Array(t));for(let r=0;r0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const i=this._targetStoreTexture.getSize();i.width===this._textureWidth&&i.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const i=this._targets.length,r=new Float32Array(i*this._textureWidth*this._textureHeight*4);let n=0;for(let a=0;a-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new f0(t);i._uniqueId=e.id;for(const r of e.targets)i.addTarget(rx.Parse(r,t));return i}}f0.EnableTextureStorage=!0;f0.MaxActiveMorphTargetsInVertexAttributeMode=8;class H1e{constructor(){this._hasHit=!1,this._hitNormal=D.Zero(),this._hitPoint=D.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class Xz extends H1e{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=D.Zero(),this._rayToWorld=D.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=D.Distance(this._rayFromWorld,this._hitPoint)}reset(e=D.Zero(),t=D.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}let j1e=class rGe{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw vi("CannonJSPlugin")}constructor(e,t=rGe.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new D(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){const r=this._joints.filter(function(n){return n.connectedImpostor===t&&n.joint===i&&n.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(t=>{t.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(t)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{typeof this.world.removeBody=="function"?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)}applyForce(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(n,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t){fe.Warn("It was not possible to create a physics body for this object.");return}const i=e.physicsBody;i&&this.removePhysicsBody(e);const r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},a=e.getParam("nativeOptions");for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&(n[o]=a[o]);e.physicsBody=new this.BJSCANNON.Body(n),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),typeof this.world.addBody=="function"?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(o){const l=i[o];e.physicsBody[o].set(l.x,l.y,l.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const r=n=>{if(!n.rotationQuaternion)return;const a=n.getPhysicsImpostor();if(a&&a.parent!==e&&n.parent){const l=n.getAbsolutePosition().subtract(n.parent.getAbsolutePosition()),c=n.rotationQuaternion.multiply(this._tmpQuaternion);a.physicsBody&&(this.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(a),new this.BJSCANNON.Vec3(l.x,l.y,l.z),new this.BJSCANNON.Quaternion(c.x,c.y,c.z,c.w)),e.physicsBody.mass+=a.getParam("mass")}n.getChildMeshes(!0).filter(o=>!!o.physicsImpostor).forEach(r)};t.filter(n=>!!n.physicsImpostor).forEach(r)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)===-1&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let r;const n=e.joint.jointData,a={pivotA:n.mainPivot?new this.BJSCANNON.Vec3().set(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z):null,pivotB:n.connectedPivot?new this.BJSCANNON.Vec3().set(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z):null,axisA:n.mainAxis?new this.BJSCANNON.Vec3().set(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z):null,axisB:n.connectedAxis?new this.BJSCANNON.Vec3().set(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z):null,maxForce:n.nativeParams.maxForce,collideConnected:!!n.collision};switch(e.joint.type){case ks.HingeJoint:case ks.Hinge2Joint:r=new this.BJSCANNON.HingeConstraint(t,i,a);break;case ks.DistanceJoint:r=new this.BJSCANNON.DistanceConstraint(t,i,n.maxDistance||2);break;case ks.SpringJoint:{const o=n;r=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:a.pivotA,localAnchorB:a.pivotB});break}case ks.LockJoint:r=new this.BJSCANNON.LockConstraint(t,i,a);break;case ks.PointToPointJoint:case ks.BallAndSocketJoint:default:r=new this.BJSCANNON.PointToPointConstraint(t,a.pivotA,i,a.pivotB,a.maxForce);break}r.collideConnected=!!n.collision,e.joint.physicsJoint=r,e.joint.type!==ks.SpringJoint?this.world.addConstraint(r):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){r.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==ks.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,n;for(r=0;ri*1e3));d++);this.time+=r;const c=this.time%i/i,u=e,h=this.bodies;for(let d=0;d!==h.length;d++){const f=h[d];f.type!==t.Body.STATIC&&f.sleepState!==t.Body.SLEEPING?(f.position.vsub(f.previousPosition,u),u.scale(c,u),f.position.vadd(u,f.interpolatedPosition)):(f.interpolatedPosition.set(f.position.x,f.position.y,f.position.z),f.interpolatedQuaternion.set(f.quaternion.x,f.quaternion.y,f.quaternion.z,f.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}j1e.DefaultPluginFactory=()=>new xZ;class Yhe{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=D.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Xz}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(r){r.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(r=>{r.afterStep(),this._tmpImpostorsArray[r.uniqueId]=r});let i=this.world.contacts;for(;i!==null;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const r=this._tmpImpostorsArray[+i.body1.name],n=this._tmpImpostorsArray[+i.body2.name];if(!r||!n){i=i.next;continue}r.onCollide({body:n.physicsBody,point:null,distance:0,impulse:0,normal:null}),n.onCollide({body:r.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){const r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){fe.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:e.getParam("mass")!==0,density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},i=[e];(o=>{o.getChildMeshes&&o.getChildMeshes().forEach(function(l){l.physicsImpostor&&i.push(l.physicsImpostor)})})(e.object);const n=o=>Math.max(o,ci),a=new Pe;i.forEach(o=>{if(!o.object.rotationQuaternion)return;const l=o.object.rotationQuaternion;a.copyFrom(l),o.object.rotationQuaternion.set(0,0,0,1),o.object.computeWorldMatrix(!0);const c=a.toEulerAngles(),u=o.getObjectExtents(),h=57.29577951308232;if(o===e){const d=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(d,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),t.pos.push(d.x),t.pos.push(d.y),t.pos.push(d.z),t.posShape.push(0,0,0),t.rotShape.push(0,0,0)}else{const d=o.object.position.clone();t.posShape.push(d.x),t.posShape.push(d.y),t.posShape.push(d.z),t.rotShape.push(c.x*h,c.y*h,c.z*h)}switch(o.object.rotationQuaternion.copyFrom(a),o.type){case oi.ParticleImpostor:fe.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case oi.SphereImpostor:{const d=u.x,f=u.y,p=u.z,m=Math.max(n(d),n(f),n(p))/2;t.type.push("sphere"),t.size.push(m),t.size.push(m),t.size.push(m);break}case oi.CylinderImpostor:{const d=n(u.x)/2,f=n(u.y);t.type.push("cylinder"),t.size.push(d),t.size.push(f),t.size.push(f);break}case oi.PlaneImpostor:case oi.BoxImpostor:default:{const d=n(u.x),f=n(u.y),p=n(u.z);t.type.push("box"),t.size.push(d),t.size.push(f),t.size.push(p);break}}o.object.rotationQuaternion=l}),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(a),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const r=e.joint.jointData,n=r.nativeParams||{};let a;const o={body1:t,body2:i,axe1:n.axe1||(r.mainAxis?r.mainAxis.asArray():null),axe2:n.axe2||(r.connectedAxis?r.connectedAxis.asArray():null),pos1:n.pos1||(r.mainPivot?r.mainPivot.asArray():null),pos2:n.pos2||(r.connectedPivot?r.connectedPivot.asArray():null),min:n.min,max:n.max,collision:n.collision||r.collision,spring:n.spring,world:this.world};switch(e.joint.type){case ks.BallAndSocketJoint:a="jointBall";break;case ks.SpringJoint:{fe.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=r;o.min=l.length||o.min,o.max=Math.max(o.min,o.max)}case ks.DistanceJoint:a="jointDistance",o.max=r.maxDistance;break;case ks.PrismaticJoint:a="jointPrisme";break;case ks.SliderJoint:a="jointSlide";break;case ks.WheelJoint:a="jointWheel";break;case ks.HingeJoint:default:a="jointHinge";break}o.type=a,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){fe.Warn(t)}}isSupported(){return this.BJSOIMO!==void 0}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new D(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new D(t.x,t.y,t.z):null}setBodyMass(e,t){const i=t===0;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,i!==void 0&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){i!==void 0?fe.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)}setLimit(e,t,i,r){const n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,i===void 0?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=i.halfWidth*2,t.y=i.halfHeight*2,t.z=i.halfDepth*2}dispose(){this.world.clear()}raycast(e,t){return fe.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){fe.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class jm{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new Pe,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new D,this._tmpContactNormal=new D,this._tmpVec3=new D,this._tmpMatrix=new he,typeof t=="function"){fe.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){fe.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=r=>{r=this.bjsAMMO.wrapPointer(r,this.bjsAMMO.btManifoldPoint);const n=r.getPositionWorldOnA(),a=r.m_normalWorldOnB;this._tmpContactPoint.x=n.x(),this._tmpContactPoint.y=n.y(),this._tmpContactPoint.z=n.z(),this._tmpContactNormal.x=a.x(),this._tmpContactNormal.y=a.y(),this._tmpContactNormal.z=a.z(),this._tmpContactImpulse=r.getAppliedImpulse(),this._tmpContactDistance=r.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new Xz,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(t==0)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(const r of i._onPhysicsCollideCallbacks)for(const n of r.otherImpostors)(i.physicsBody.isActive()||n.physicsBody.isActive())&&this._isImpostorPairInContact(i,n)&&(i.onCollide({body:n.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),n.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===oi.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let r,n,a,o,l;const c=new Array;for(let d=0;d{this.bjsAMMO.destroy(t)}),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i||e.joint.physicsJoint)return;const r=e.joint.jointData;r.mainPivot||(r.mainPivot=new D(0,0,0)),r.connectedPivot||(r.connectedPivot=new D(0,0,0));let n;switch(e.joint.type){case ks.DistanceJoint:{const a=r.maxDistance;a&&(r.mainPivot=new D(0,-a/2,0),r.connectedPivot=new D(0,a/2,0));const o=this._tmpAmmoVectorA;o.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const l=this._tmpAmmoVectorB;l.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),n=new this.bjsAMMO.btPoint2PointConstraint(t,i,o,l);break}case ks.HingeJoint:{r.mainAxis||(r.mainAxis=new D(0,0,0)),r.connectedAxis||(r.connectedAxis=new D(0,0,0));const a=this._tmpAmmoVectorA;a.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z);const l=this._tmpAmmoVectorC;l.setValue(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z);const c=this._tmpAmmoVectorD;c.setValue(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z),n=new this.bjsAMMO.btHingeConstraint(t,i,a,o,l,c);break}case ks.BallAndSocketJoint:{const a=this._tmpAmmoVectorA;a.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),n=new this.bjsAMMO.btPoint2PointConstraint(t,i,a,o);break}default:{fe.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const a=this._tmpAmmoVectorA;a.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),n=new this.bjsAMMO.btPoint2PointConstraint(t,i,a,o);break}}this.world.addConstraint(n,!e.joint.jointData.collision),e.joint.physicsJoint=n}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let n=i.getIndices();n||(n=[]);let a=i.getVerticesData($.PositionKind);a||(a=[]);let o;if(t&&t!==i){let c;t.rotationQuaternion?c=t.rotationQuaternion:t.rotation?c=Pe.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):c=Pe.Identity(),he.Compose(D.One(),c,t.position).invertToRef(this._tmpMatrix),o=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else he.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=this._tmpMatrix;const l=n.length/3;for(let c=0;c{r+=this._addMeshVerts(e,t,c)})}return r}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){t.getIndices();let i=t.getVerticesData($.PositionKind);i||(i=[]);let r=t.getVerticesData($.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);const n=[],a=[];for(let l=0;ld*d),l=(d,f)=>d+f;if(o.reduce(l)===0)t=n.length,i=t/3-1,this._tmpAmmoVectorA.setValue(n[0],n[1],n[2]),this._tmpAmmoVectorB.setValue(n[t-3],n[t-2],n[t-1]);else{e._isFromLine=!1;const d=e.getParam("path");if(e.getParam("shape")===null)return fe.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=d.length,i=t-1,this._tmpAmmoVectorA.setValue(d[0].x,d[0].y,d[0].z),this._tmpAmmoVectorB.setValue(d[t-1].x,d[t-1].y,d[t-1].z)}e.segments=i;let u=e.getParam("fixedPoints");u=u>3?3:u;const h=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,u);return h.get_m_cfg().set_collisions(17),h}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),t==null&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let n=i.getIndices();n||(n=[]);let a=i.getVerticesData($.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);const o=n.length/3;for(let l=0;l{r+=this._addHullVerts(e,t,l)})}return r}_createShape(e,t=!1){const i=e.object;let r;const n=e.getObjectExtents();if(!t){const a=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];r=new this.bjsAMMO.btCompoundShape;let o=0;if(a.forEach(l=>{const c=l.getPhysicsImpostor();if(c){if(c.type==oi.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const u=this._createShape(c),h=l.parent.getWorldMatrix().clone(),d=new D;h.decompose(d),this._tmpAmmoTransform.getOrigin().setValue(l.position.x*d.x,l.position.y*d.y,l.position.z*d.z),this._tmpAmmoQuaternion.setValue(l.rotationQuaternion.x,l.rotationQuaternion.y,l.rotationQuaternion.z,l.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,u),c.dispose(),o++}}),o>0){if(e.type!=oi.NoImpostor){const l=this._createShape(e,!0);l&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,l))}return r}else this.bjsAMMO.destroy(r),r=null}switch(e.type){case oi.SphereImpostor:if(At.WithinEpsilon(n.x,n.y,1e-4)&&At.WithinEpsilon(n.x,n.z,1e-4))r=new this.bjsAMMO.btSphereShape(n.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const a=[this._tmpAmmoVectorA],o=[1];r=new this.bjsAMMO.btMultiSphereShape(a,o,1),this._tmpAmmoVectorA.setValue(n.x/2,n.y/2,n.z/2),r.setLocalScaling(this._tmpAmmoVectorA)}break;case oi.CapsuleImpostor:{const a=n.x/2;r=new this.bjsAMMO.btCapsuleShape(a,n.y-a*2)}break;case oi.CylinderImpostor:this._tmpAmmoVectorA.setValue(n.x/2,n.y/2,n.z/2),r=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case oi.PlaneImpostor:case oi.BoxImpostor:this._tmpAmmoVectorA.setValue(n.x/2,n.y/2,n.z/2),r=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case oi.MeshImpostor:if(e.getParam("mass")==0){if(this.onCreateCustomMeshImpostor)r=this.onCreateCustomMeshImpostor(e);else{const a=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(a),this._addMeshVerts(a,i,i)==0?r=new this.bjsAMMO.btCompoundShape:r=new this.bjsAMMO.btBvhTriangleMeshShape(a)}break}case oi.ConvexHullImpostor:{if(this.onCreateCustomConvexHullImpostor)r=this.onCreateCustomConvexHullImpostor(e);else{const a=new this.bjsAMMO.btConvexHullShape;this._addHullVerts(a,i,i)==0?(e._pluginData.toDispose.push(a),r=new this.bjsAMMO.btCompoundShape):r=a}break}case oi.NoImpostor:r=new this.bjsAMMO.btSphereShape(n.x/2);break;case oi.CustomImpostor:r=this._createCustom(e);break;case oi.SoftbodyImpostor:r=this._createSoftbody(e);break;case oi.ClothImpostor:r=this._createCloth(e);break;case oi.RopeImpostor:r=this._createRope(e);break;default:fe.Warn("The impostor type is not currently supported by the ammo plugin.");break}return r}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>ci||Math.abs(r.getOrigin().y()-t.y)>ci||Math.abs(r.getOrigin().z()-t.z)>ci||Math.abs(r.getRotation().x()-i.x)>ci||Math.abs(r.getRotation().y()-i.y)>ci||Math.abs(r.getRotation().z()-i.z)>ci||Math.abs(r.getRotation().w()-i.w)>ci)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),e.mass==0){const n=e.physicsBody.getMotionState();n&&n.setWorldTransform(r)}else e.physicsBody.activate()}isSupported(){return this.bjsAMMO!==void 0}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(e.soft?t=e.physicsBody.linearVelocity():t=e.physicsBody.getLinearVelocity(),!t)return null;const i=new D(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(e.soft?t=e.physicsBody.angularVelocity():t=e.physicsBody.getAngularVelocity(),!t)return null;const i=new D(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(fe.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===oi.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):fe.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(fe.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=t<0?0:t,t=t>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):fe.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(fe.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):fe.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(fe.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):fe.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,n=1,a=!1){const o=e.segments,l=Math.round((o-1)*i),c=Math.round((o-1)*r),u=o-1-c,h=l+o*u;e.physicsBody.appendAnchor(h,t.physicsBody,a,n)}appendHook(e,t,i,r=1,n=!1){const a=Math.round(e.segments*i);e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){fe.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){fe.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}jm._DISABLE_COLLISION_FLAG=4;jm._KINEMATIC_FLAG=2;jm._DISABLE_DEACTIVATION_FLAG=4;Oa.prototype.removeReflectionProbe=function(s){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(s);return e!==-1&&this.reflectionProbes.splice(e,1),e};Oa.prototype.addReflectionProbe=function(s){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(s)};class cT{constructor(e,t,i,r=!0,n=!1,a=!1){if(this.name=e,this._viewMatrix=he.Identity(),this._target=D.Zero(),this._add=D.Zero(),this._invertYAxis=!1,this.position=D.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let u=0;u<6;++u)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${u}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(n){const u=this._scene.getEngine().getCaps();u.textureHalfFloatRender?o=2:u.textureFloatRender&&(o=1)}this._renderTargetTexture=new Rs(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!a,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(u=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[u]),i.getSceneUniformBuffer().unbindEffect()),u){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1);break}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const h=i.useRightHandedSystem?he.LookAtRHToRef:he.LookAtLHToRef,d=i.useRightHandedSystem?he.PerspectiveFovRH:he.PerspectiveFovLH;h(this.position,this._target,D.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=d(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position});let c;this._renderTargetTexture.onBeforeBindObservable.add(()=>{var u,h;this._currentSceneUBO=i.getSceneUniformBuffer(),(h=(u=i.getEngine())._debugPushGroup)==null||h.call(u,`reflection probe generation for ${e}`,1),c=this._scene.imageProcessingConfiguration.applyByPostProcess,a&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var u,h;i.imageProcessingConfiguration.applyByPostProcess=c,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),(h=(u=i.getEngine())._debugPopGroup)==null||h.call(u,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(e!==-1&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const t=this._parentContainer.reflectionProbes.indexOf(this);t>-1&&this._parentContainer.reflectionProbes.splice(t,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const t of this._sceneUBOs)t.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=qe.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let n=0;nr||new cT(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i),r.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}F([Hw()],cT.prototype,"_attachedMesh",void 0);F([Pn()],cT.prototype,"position",void 0);class eAt{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,n){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=n,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class bee extends eAt{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new Ae,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Ze(1,1,1,1),this.position=D.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,n=null){this._onAnimationEnd=n,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance)&&(r=o,t))break}return r||new Ko};gt.prototype._internalMultiPickSprites=function(s,e,t){if(!Ko)return null;let i=[];if(!t){if(!this.activeCamera)return null;t=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;rt.actionManager?t.isPickable&&t.actionManager.hasPointerTriggers:!1}register(){this.scene._pointerMoveStage.registerStep(ot.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ot.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ot.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,n){const a=this.scene.pickSprite(t,i,this._spritePredicate,r,n);return a&&(a.ray=e?e.ray:null),a}_pointerMove(e,t,i,r,n){const a=this.scene;return r?a.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,a.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite?(a.setPointerOverSprite(i.pickedSprite),!a.doNotHandleCursors&&n&&(a._pointerOverSprite&&a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?n.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:n.style.cursor=a.hoverCursor)):a.setPointerOverSprite(null)),i}_pointerDown(e,t,i,r){const n=this.scene;if(n._pickedDownSprite=null,n.spriteManagers&&n.spriteManagers.length>0&&(i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager)){switch(n._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Hn.CreateNewFromSprite(i.pickedSprite,n,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Hn.CreateNewFromSprite(i.pickedSprite,n,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Hn.CreateNewFromSprite(i.pickedSprite,n,r));break}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Hn.CreateNewFromSprite(i.pickedSprite,n,r))}return i}_pointerUp(e,t,i,r,n){const a=this.scene;if(a.spriteManagers&&a.spriteManagers.length>0){const o=a.pickSprite(e,t,this._spritePredicate,!1,a.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(7,Hn.CreateNewFromSprite(o.pickedSprite,a,r)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(1,Hn.CreateNewFromSprite(o.pickedSprite,a,r)),n&&o.pickedSprite.actionManager.processTrigger(6,Hn.CreateNewFromSprite(o.pickedSprite,a,r)))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==o.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(16,Hn.CreateNewFromSprite(a._pickedDownSprite,a,r)))}return i}}class Cee{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){var i;const t=!!((i=this._scene)!=null&&i.getEngine().getCaps().fragmentDepthSupported);e&&!t&&fe.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i=.01,r=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._shaderLanguage=0,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._shadersLoaded=!1,this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Mo(e,this._vertexData,!0,this._vertexBufferSize);const n=this._buffer.createVertexBuffer($.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o=6,l;if(this._useInstancing){const d=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Mo(e,d,!1,2),l=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else l=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;const c=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer($.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[$.PositionKind]=n,this._vertexBuffers.options=a,this._vertexBuffers.offsets=l,this._vertexBuffers.inverts=c,this._vertexBuffers.cellInfo=u,this._vertexBuffers[$.ColorKind]=h,this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._engine.isWebGPU&&!Cee.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Ue(()=>Promise.resolve().then(()=>ePt),void 0),Ue(()=>Promise.resolve().then(()=>J5t),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>$5t),void 0),Ue(()=>Promise.resolve().then(()=>Q5t),void 0)]),this._shadersLoaded=!0,this._createEffects()}_createEffects(){var t,i;(t=this._drawWrapperBase)==null||t.dispose(),(i=this._drawWrapperDepth)==null||i.dispose(),this._drawWrapperBase=new Ro(this._engine),this._drawWrapperDepth=new Ro(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+=`#define PIXEL_PERFECT `),this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0&&this._fogEnabled&&(e+=`#define FOG `),this._useLogarithmicDepth&&(e+=`#define LOGARITHMICDEPTH `),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[$.PositionKind,"options","offsets","inverts","cellInfo",$.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e,void 0,void 0,void 0,void 0,this._shaderLanguage),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,r,n=null){if(!this._shadersLoaded||!this.texture||!this.texture.isReady()||!e.length)return;const a=this._drawWrapperBase,o=this._drawWrapperDepth,l=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0,c=a.effect;if(!c.isReady())return;const u=this._engine,h=!!(this._scene&&this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),f=Math.min(this._capacity,e.length);let p=0,m=!0;for(let v=0;v>0;t._xOffset=(t.cellIndex-u*c)*this.cellWidth/n.width,t._yOffset=u*this.cellHeight/n.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[l]=t.position.x,this._vertexData[l+1]=t.position.y,this._vertexData[l+2]=t.position.z,this._vertexData[l+3]=t.angle,this._vertexData[l+4]=t.width,this._vertexData[l+5]=t.height,this._useInstancing?l-=2:(this._vertexData[l+6]=i,this._vertexData[l+7]=r),a?this._vertexData[l+8]=t.invertU?0:1:this._vertexData[l+8]=t.invertU?1:0,this._vertexData[l+9]=t.invertV?1:0,this._vertexData[l+10]=t._xOffset,this._vertexData[l+11]=t._yOffset,this._vertexData[l+12]=t._xSize/n.width,this._vertexData[l+13]=t._ySize/n.height,this._vertexData[l+14]=t.color.r,this._vertexData[l+15]=t.color.g,this._vertexData[l+16]=t.color.b,this._vertexData[l+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i{h.cellRef||(h.cellIndex=0);const f=h.cellIndex;typeof f=="number"&&isFinite(f)&&Math.floor(f)===f&&(h.cellRef=this._spriteMap[h.cellIndex]),h._xOffset=this._cellData[h.cellRef].frame.x/d.width,h._yOffset=this._cellData[h.cellRef].frame.y/d.height,h._xSize=this._cellData[h.cellRef].frame.w,h._ySize=this._cellData[h.cellRef].frame.h},n||(n=Rt.LastCreatedScene),n._getComponent(ot.NAME_SPRITE)||n._addComponent(new sGe(n)),this._fromPacked=l,this._scene=n;const u=this._scene.getEngine();if(this._spriteRenderer=new Cee(u,i,a,n),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(r!==void 0)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new xe(t,n,!0,!1,o)),this._fromPacked&&this._makePacked(t,c)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(t!==null)try{let i;if(typeof t=="string"?i=JSON.parse(t):i=t,i.frames.length){const n={};for(let a=0;a0);const n=e.substring(0,r-1)+".json",a=()=>{fe.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=l=>{try{const c=JSON.parse(l),u=Reflect.ownKeys(c.frames);this._spriteMap=u,this._packedAndReady=!0,this._cellData=c.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Me.LoadFile(n,o,void 0,void 0,!1,a)}}_checkTextureAlpha(e,t,i,r,n){if(!e.useAlphaForPicking||!this.texture)return!0;const a=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(a.width*a.height*4),this.texture.readPixels(0,0,this._textureContent));const o=se.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const l=(o.x-r.x)/(n.x-r.x),c=1-(o.y-r.y)/(n.y-r.y),u=e._xOffset*a.width+l*e._xSize|0,h=e._yOffset*a.height+c*e._ySize|0;return this._textureContent[(u+h*a.width)*4+3]>.5}intersects(e,t,i,r){const n=Math.min(this.capacity,this.sprites.length),a=D.Zero(),o=D.Zero();let l=Number.MAX_VALUE,c=null;const u=se.Vector3[0],h=se.Vector3[1],d=t.getViewMatrix();let f=e,p=e;for(let m=0;m_){if(!this._checkTextureAlpha(g,f,_,a,o))continue;if(p=f,l=_,c=g,r)break}}}}if(c){const m=new Ko;d.invertToRef(se.Matrix[0]),m.hit=!0,m.pickedSprite=c,m.distance=l;const g=se.Vector3[2];return g.copyFrom(p.direction),g.normalize(),g.scaleInPlace(l),p.origin.addToRef(g,u),m.pickedPoint=D.TransformCoordinates(u,se.Matrix[0]),m}return null}multiIntersects(e,t,i){const r=Math.min(this.capacity,this.sprites.length),n=D.Zero(),a=D.Zero();let o;const l=[],c=se.Vector3[0].copyFromFloats(0,0,0),u=se.Vector3[1].copyFromFloats(0,0,0),h=t.getViewMatrix();for(let d=0;d{const o=new On;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),c=Xm.Parse(l,i||Rt.LastCreatedScene,r);e&&(c.name=e),n(c)}else a("Unable to load the sprite manager")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return e==="_BLANK"?Promise.resolve(new Xm("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,n)=>{const a=new On;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.spriteManager),c=Xm.Parse(l,t||Rt.LastCreatedScene,i);c.snippetId=e,r(c)}else n("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}Xm.SnippetUrl="https://snippet.babylonjs.com";Xm.CreateFromSnippetAsync=Xm.ParseFromSnippetAsync;var tAt=!0;class XB{}XB.LoaderInjectedPhysicsEngine=void 0;let x5={},ky={};const aMe=(s,e,t,i)=>{if(!e.materials)return null;for(let r=0,n=e.materials.length;r{for(const i in e)if(s.name===e[i])return t.push(s.id),!0;return s.parentId!==void 0&&t.indexOf(s.parentId)!==-1?(t.push(s.id),!0):!1},w5=(s,e)=>s+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),nGe=(s,e)=>{const t=e;if(e._waitingData.lods){if(e._waitingData.lods.ids&&e._waitingData.lods.ids.length>0){const i=e._waitingData.lods.ids,r=t.isEnabled(!1);if(e._waitingData.lods.distances){const n=e._waitingData.lods.distances;if(n.length>=i.length){const a=n.length>i.length?n[n.length-1]:0;t.setEnabled(!1);for(let o=0;o0&&t.addLODLevel(a,null),r===!0&&t.setEnabled(!0)}else Me.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},hY=(s,e,t)=>{if(typeof s!="number"){const r=t.getLastEntryById(s);return r&&e!==void 0&&e!==null?r.instances[parseInt(e)]:r}const i=x5[s];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},AZ=(s,e)=>typeof s!="number"?e.getLastMaterialById(s,!0):ky[s],oMe=(s,e,t,i,r=!1)=>{const n=new _z(s);let a="importScene has failed JSON parse";try{var o=JSON.parse(e);a="";const l=Ys.loggingLevel===Ys.DETAILED_LOGGING;let c,u;if(o.environmentTexture!==void 0&&o.environmentTexture!==null){const d=o.isPBR!==void 0?o.isPBR:!0;if(o.environmentTextureType&&o.environmentTextureType==="BABYLON.HDRCubeTexture"){const f=o.environmentTextureSize?o.environmentTextureSize:128,p=new e_((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,s,f,!0,!d,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(p.rotationY=o.environmentTextureRotationY),s.environmentTexture=p}else if(typeof o.environmentTexture=="object"){const f=_a.Parse(o.environmentTexture,s,t);s.environmentTexture=f}else if(o.environmentTexture.endsWith(".env")){const f=new _a((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,s,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),s.environmentTexture=f}else{const f=_a.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,s,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),s.environmentTexture=f}if(o.createDefaultSkybox===!0){const f=s.activeCamera!==void 0&&s.activeCamera!==null?(s.activeCamera.maxZ-s.activeCamera.minZ)/2:1e3,p=o.skyboxBlurLevel||0;s.createDefaultSkybox(s.environmentTexture,d,f,p)}n.environmentTexture=s.environmentTexture}if(o.environmentIntensity!==void 0&&o.environmentIntensity!==null&&(s.environmentIntensity=o.environmentIntensity),o.lights!==void 0&&o.lights!==null)for(c=0,u=o.lights.length;c{n.textures.indexOf(m)==-1&&(n.textures.push(m),m._parentContainer=n)}))}if(o.multiMaterials!==void 0&&o.multiMaterials!==null)for(c=0,u=o.multiMaterials.length;c{n.textures.indexOf(m)==-1&&(n.textures.push(m),m._parentContainer=n)})}if(o.morphTargetManagers!==void 0&&o.morphTargetManagers!==null)for(const d of o.morphTargetManagers){const f=f0.Parse(d,s);n.morphTargetManagers.push(f),f._parentContainer=n}if(o.skeletons!==void 0&&o.skeletons!==null)for(c=0,u=o.skeletons.length;c{p&&(n.geometries.push(p),p._parentContainer=n)})}if(o.transformNodes!==void 0&&o.transformNodes!==null)for(c=0,u=o.transformNodes.length;c{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(AZ(f,s))}),d._waitingSubMaterialsUniqueIds=[]}),s.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=AZ(d._waitingMaterialId,s),d._waitingMaterialId=null)}),c=0,u=s.skeletons.length;c{if(f._waitingTransformNodeId){const p=s.getLastEntryById(f._waitingTransformNodeId);p&&f.linkTransformNode(p),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(c=0,u=s.meshes.length;c0){for(let f=0;f0){for(let f=0;f{d._loadedUniqueId=""}),Oa.Parse(o,s,n,t),c=0,u=s.meshes.length;cs.indexOf("babylon")!==-1,importMesh:(s,e,t,i,r,n,a,o)=>{var u;let l="importMesh has failed JSON parse";try{var c=JSON.parse(t);l="";const h=Ys.loggingLevel===Ys.DETAILED_LOGGING;s?Array.isArray(s)||(s=[s]):s=null;const d=[],f=new Map,p=[];if(c.transformNodes!==void 0&&c.transformNodes!==null)for(let m=0,g=c.transformNodes.length;m{T===!0||!c.geometries[w]||!Array.isArray(c.geometries[w])||c.geometries[w].forEach(P=>{if(P.id===b.geometryId){switch(w){case"vertexData":So.Parse(P,e,i);break}T=!0}})}),T===!1&&fe.Warn("Geometry not found for mesh "+b.id)}if(b.materialUniqueId||b.materialId){const T=b.materialUniqueId?_:g;let w=T.indexOf(b.materialUniqueId||b.materialId)!==-1;if(w===!1&&c.multiMaterials!==void 0&&c.multiMaterials!==null){const P=(M,R)=>{T.push(M);const I=aMe(R,c,e,i);I&&I.material&&(ky[I.parsedMaterial.uniqueId||I.parsedMaterial.id]=I.material,l+=` Material `+I.material.toString(h))};for(let M=0,R=c.multiMaterials.length;MP(k,V=>V.uniqueId===k)):I.materials.forEach(k=>P(k,V=>V.id===k)),T.push(I.uniqueId||I.id);const L=Zd.ParseMultiMaterial(I,e);ky[I.uniqueId||I.id]=L,L&&(w=!0,l+=` Multi-Material `+L.toString(h));break}}}if(w===!1){T.push(b.materialUniqueId||b.materialId);const P=aMe(M=>b.materialUniqueId&&M.uniqueId===b.materialUniqueId||M.id===b.materialId,c,e,i);!P||!P.material?fe.Warn("Material not found for mesh "+b.id):(ky[P.parsedMaterial.uniqueId||P.parsedMaterial.id]=P.material,l+=` Material `+P.material.toString(h))}}if(b.skeletonId!==null&&b.skeletonId!==void 0&&c.skeletonId!==-1&&c.skeletons!==void 0&&c.skeletons!==null&&!(m.indexOf(b.skeletonId)>-1))for(let w=0,P=c.skeletons.length;w-1&&c.morphTargetManagers!==void 0&&c.morphTargetManagers!==null&&!(y.indexOf(b.morphTargetManagerId)>-1))for(let w=0,P=c.morphTargetManagers.length;w{x._waitingSubMaterialsUniqueIds.forEach(A=>{x.subMaterials.push(AZ(A,e))}),x._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(x=>{x._waitingMaterialId!==null&&(x.material=AZ(x._waitingMaterialId,e),x._waitingMaterialId=null)});for(let x=0,A=e.transformNodes.length;x-1&&p.splice(T,1)}v._waitingParentId=null}v._waitingData.lods&&nGe(e,v)}for(const x of p)x.dispose();for(let x=0,A=e.skeletons.length;x{if(C._waitingTransformNodeId){const T=e.getLastEntryById(C._waitingTransformNodeId);T&&C.linkTransformNode(T),C._waitingTransformNodeId=null}}),b._hasWaitingData=null)}for(let x=0,A=e.meshes.length;x{m._loadedUniqueId=""}),!0}catch(h){const d=w5("importMesh",c?c.producer:"Unknown")+l;if(o)o(d,h);else throw fe.Log(d),h}finally{l!==null&&Ys.loggingLevel!==Ys.NO_LOGGING&&fe.Log(w5("importMesh",c?c.producer:"Unknown")+(Ys.loggingLevel!==Ys.MINIMAL_LOGGING?l:"")),ky={}}return!1},load:(s,e,t,i)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(e);switch(r="",n.useDelayedTextureLoading!==void 0&&n.useDelayedTextureLoading!==null&&(s.useDelayedTextureLoading=n.useDelayedTextureLoading&&!Ys.ForceFullSceneLoadingForIncremental),n.autoClear!==void 0&&n.autoClear!==null&&(s.autoClear=n.autoClear),n.clearColor!==void 0&&n.clearColor!==null&&(s.clearColor=Ze.FromArray(n.clearColor)),n.ambientColor!==void 0&&n.ambientColor!==null&&(s.ambientColor=Re.FromArray(n.ambientColor)),n.gravity!==void 0&&n.gravity!==null&&(s.gravity=D.FromArray(n.gravity)),n.useRightHandedSystem!==void 0&&(s.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode!==void 0&&n.fogMode!==null&&(s.fogMode=n.fogMode),n.fogColor!==void 0&&n.fogColor!==null&&(s.fogColor=Re.FromArray(n.fogColor)),n.fogStart!==void 0&&n.fogStart!==null&&(s.fogStart=n.fogStart),n.fogEnd!==void 0&&n.fogEnd!==null&&(s.fogEnd=n.fogEnd),n.fogDensity!==void 0&&n.fogDensity!==null&&(s.fogDensity=n.fogDensity),r+=" Fog mode for scene: ",s.fogMode){case 0:r+=`none `;break;case 1:r+=`exp `;break;case 2:r+=`exp2 `;break;case 3:r+=`linear `;break}if(n.physicsEnabled){let o;n.physicsEngine==="cannon"||n.physicsEngine===xZ.name?o=new xZ(void 0,void 0,XB.LoaderInjectedPhysicsEngine):n.physicsEngine==="oimo"||n.physicsEngine===Yhe.name?o=new Yhe(void 0,XB.LoaderInjectedPhysicsEngine):(n.physicsEngine==="ammo"||n.physicsEngine===jm.name)&&(o=new jm(void 0,XB.LoaderInjectedPhysicsEngine,void 0)),r=" Physics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+` enabled `;const l=n.gravity?D.FromArray(n.gravity):n.physicsGravity?D.FromArray(n.physicsGravity):null;s.enablePhysics(l,o)}return n.metadata!==void 0&&n.metadata!==null&&(s.metadata=n.metadata),n.collisionsEnabled!==void 0&&n.collisionsEnabled!==null&&(s.collisionsEnabled=n.collisionsEnabled),oMe(s,e,t,i,!0)?(n.autoAnimate&&s.beginAnimation(s,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),n.activeCameraID!==void 0&&n.activeCameraID!==null&&s.setActiveCameraById(n.activeCameraID),!0):!1}catch(a){const o=w5("importScene",n?n.producer:"Unknown")+r;if(i)i(o,a);else throw fe.Log(o),a}finally{r!==null&&Ys.loggingLevel!==Ys.NO_LOGGING&&fe.Log(w5("importScene",n?n.producer:"Unknown")+(Ys.loggingLevel!==Ys.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(s,e,t,i)=>oMe(s,e,t,i)});const rAt="backgroundUboDeclaration",sAt=`uniform vPrimaryColor: vec4f;uniform vPrimaryColorShadow: vec4f;uniform vDiffuseInfos: vec2f;uniform vReflectionInfos: vec2f;uniform diffuseMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform fFovMultiplier: f32;uniform pointSize: f32;uniform shadowLevel: f32;uniform alpha: f32;uniform vBackgroundCenter: vec3f;uniform vReflectionControl: vec4f;uniform projectedGroundInfos: vec2f; #include `;de.IncludesShadersStoreWGSL[rAt]=sAt;const nAt="fogVertexDeclaration",aAt=`#ifdef FOG varying vFogDistance: vec3f; #endif `;de.IncludesShadersStoreWGSL[nAt]=aAt;const aGe="lightVxUboDeclaration",oGe=`#ifdef LIGHT{X} struct Light{X} {vLightData: vec4f, vLightDiffuse: vec4f, vLightSpecular: vec4f, #ifdef SPOTLIGHT{X} vLightDirection: vec4f, vLightFalloff: vec4f, #elif defined(POINTLIGHT{X}) vLightFalloff: vec4f, #elif defined(HEMILIGHT{X}) vLightGround: vec3f, #endif shadowsInfo: vec4f, depthValues: vec2f} ;var light{X} : Light{X}; #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f; #elif defined(SHADOWCUBE{X}) #else varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f; #endif #endif #endif `;de.IncludesShadersStoreWGSL[aGe]=oGe;const lGe={name:aGe,shader:oGe},oAt=Object.freeze(Object.defineProperty({__proto__:null,lightVxUboDeclarationWGSL:lGe},Symbol.toStringTag,{value:"Module"})),lAt="logDepthDeclaration",cAt=`#ifdef LOGARITHMICDEPTH uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32; #endif `;de.IncludesShadersStoreWGSL[lAt]=cAt;const uAt="fogVertex",hAt=`#ifdef FOG vertexOutputs.vFogDistance=(scene.view*worldPos).xyz; #endif `;de.IncludesShadersStoreWGSL[uAt]=hAt;const cGe="shadowsVertex",uGe=`#ifdef SHADOWS #if defined(SHADOWCSM{X}) vertexOutputs.vPositionFromCamera{X}=scene.view*worldPos; #if SHADOWCSMNUM_CASCADES{X}>0 vertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #if SHADOWCSMNUM_CASCADES{X}>1 vertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #if SHADOWCSMNUM_CASCADES{X}>2 vertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #if SHADOWCSMNUM_CASCADES{X}>3 vertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) vertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #endif `;de.IncludesShadersStoreWGSL[cGe]=uGe;const hGe={name:cGe,shader:uGe},dAt=Object.freeze(Object.defineProperty({__proto__:null,shadowsVertexWGSL:hGe},Symbol.toStringTag,{value:"Module"})),fAt="logDepthVertex",pAt=`#ifdef LOGARITHMICDEPTH vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant; #endif `;de.IncludesShadersStoreWGSL[fAt]=pAt;const dGe="backgroundVertexShader",fGe=`#include #include attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif #include #include #include varying vPositionW: vec3f; #ifdef NORMAL varying vNormalW: vec3f; #endif #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #ifdef MAINUV1 varying vMainUV1: vec2f; #endif #ifdef MAINUV2 varying vMainUV2: vec2f; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 varying vDiffuseUV: vec2f; #endif #include #include #include[0..maxSimultaneousLights] #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN #ifdef REFLECTIONMAP_SKYBOX vertexOutputs.vPositionUVW=input.position; #endif #include #include #include #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);} else {vertexOutputs.position=scene.viewProjectionR*finalWorld* vec4f(input.position,1.0);} #else vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0); #endif var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.vPositionW= worldPos.xyz; #ifdef NORMAL var normalWorld: mat3x3f=mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vertexOutputs.vNormalW=normalize(normalWorld*input.normal); #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(input.position,0.0)).xyz); #ifdef EQUIRECTANGULAR_RELFECTION_FOV var screenToWorld: mat3x3f=inverseMat3( mat3x3f(finalWorld*scene.viewProjection));var segment: vec3f=mix(vertexOutputs.vDirectionW,screenToWorld* vec3f(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vertexOutputs.vDirectionW=normalize(segment);} else {vertexOutputs.vDirectionW=normalize(vertexOutputs.vDirectionW+(vertexOutputs.vDirectionW-segment));} #endif #endif #ifndef UV1 var uv: vec2f=vec2f(0.,0.); #else var uv=input.uv; #endif #ifndef UV2 var uv2: vec2f=vec2f(0.,0.); #else var uv2=input.uv2; #endif #ifdef MAINUV1 vertexOutputs.vMainUV1=uv; #endif #ifdef MAINUV2 vertexOutputs.vMainUV2=uv2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 if (uniforms.vDiffuseInfos.x==0.) {vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv,1.0,0.0)).xy;} else {vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv2,1.0,0.0)).xy;} #endif #include #include #include[0..maxSimultaneousLights] #ifdef VERTEXCOLOR vertexOutputs.vColor=color; #endif #include #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStoreWGSL[dGe]=fGe;const pGe={name:dGe,shader:fGe},mAt=Object.freeze(Object.defineProperty({__proto__:null,backgroundVertexShaderWGSL:pGe},Symbol.toStringTag,{value:"Module"})),mGe="reflectionFunction",gGe=`fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f {var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); } fn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f {var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); } fn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f {var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);} fn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f {var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);} fn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f {var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;} fn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f {var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz; #ifdef INVERTCUBICMAP coords.y*=-1.0; #endif return coords;} fn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f {var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz; #ifdef INVERTCUBICMAP coords.y*=-1.0; #endif return coords;} fn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f {return (reflectionMatrix*(view*worldPos)).xyz;} fn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f {return (reflectionMatrix* vec4f(positionW,1.)).xyz;} #ifdef REFLECTION fn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f { #ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); #endif #ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); #endif #ifdef REFLECTIONMAP_EQUIRECTANGULAR return computeEquirectangularCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); #endif #ifdef REFLECTIONMAP_SPHERICAL return computeSphericalCoords(worldPos,worldNormal,scene.view,uniforms.reflectionMatrix); #endif #ifdef REFLECTIONMAP_PLANAR return computePlanarCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); #endif #ifdef REFLECTIONMAP_CUBIC #ifdef USE_LOCAL_REFLECTIONMAP_CUBIC return computeCubicLocalCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix,uniforms.vReflectionSize,uniforms.vReflectionPosition); #else return computeCubicCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); #endif #endif #ifdef REFLECTIONMAP_PROJECTION return computeProjectionCoords(worldPos,scene.view,uniforms.reflectionMatrix); #endif #ifndef REFLECTIONMAP_CUBIC #ifdef REFLECTIONMAP_SKYBOX return computeSkyBoxCoords(fragmentInputs.vPositionUVW,uniforms.reflectionMatrix); #endif #endif #ifdef REFLECTIONMAP_EXPLICIT return vec3f(0,0,0); #endif } #endif `;de.IncludesShadersStoreWGSL[mGe]=gGe;const _Ge={name:mGe,shader:gGe},gAt=Object.freeze(Object.defineProperty({__proto__:null,reflectionFunctionWGSL:_Ge},Symbol.toStringTag,{value:"Module"})),vGe="imageProcessingDeclaration",yGe=`#ifdef EXPOSURE uniform exposureLinear: f32; #endif #ifdef CONTRAST uniform contrast: f32; #endif #if defined(VIGNETTE) || defined(DITHER) uniform vInverseScreenSize: vec2f; #endif #ifdef VIGNETTE uniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f; #endif #ifdef COLORCURVES uniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f; #endif #ifdef COLORGRADING #ifdef COLORGRADING3D var txColorTransformSampler: sampler;var txColorTransform: texture_3d; #else var txColorTransformSampler: sampler;var txColorTransform: texture_2d; #endif uniform colorTransformSettings: vec4f; #endif #ifdef DITHER uniform ditherIntensity: f32; #endif `;de.IncludesShadersStoreWGSL[vGe]=yGe;const xGe={name:vGe,shader:yGe},_At=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingDeclarationWGSL:xGe},Symbol.toStringTag,{value:"Module"})),AGe="lightUboDeclaration",bGe=`#ifdef LIGHT{X} struct Light{X} {vLightData: vec4f, vLightDiffuse: vec4f, vLightSpecular: vec4f, #ifdef SPOTLIGHT{X} vLightDirection: vec4f, vLightFalloff: vec4f, #elif defined(POINTLIGHT{X}) vLightFalloff: vec4f, #elif defined(HEMILIGHT{X}) vLightGround: vec3f, #endif shadowsInfo: vec4f, depthValues: vec2f} ;var light{X} : Light{X}; #ifdef PROJECTEDLIGHTTEXTURE{X} uniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d; #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array; #if defined(SHADOWPCSS{X}) var shadowTexture{X}Sampler: sampler_comparison; var shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32; #elif defined(SHADOWPCF{X}) var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array; #else var shadowTexture{X}Sampler: sampler; var shadowTexture{X}: texture_2d_array; #endif #ifdef SHADOWCSMDEBUG{X} const vCascadeColorsMultiplier{X}: array=array ( vec3f ( 1.5,0.0,0.0 ), vec3f ( 0.0,1.5,0.0 ), vec3f ( 0.0,0.0,5.5 ), vec3f ( 1.5,0.0,5.5 ), vec3f ( 1.5,1.5,0.0 ), vec3f ( 1.0,1.0,1.0 ), vec3f ( 0.0,1.0,5.5 ), vec3f ( 0.5,3.5,0.75 ) ); #endif #elif defined(SHADOWCUBE{X}) var shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube; #else varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32; #if defined(SHADOWPCSS{X}) var shadowTexture{X}Sampler: sampler_comparison; var shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; var depthTexture{X}: texture_2d; #elif defined(SHADOWPCF{X}) var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d; #else var shadowTexture{X}Sampler: sampler; var shadowTexture{X}: texture_2d; #endif uniform lightMatrix{X}: mat4x4f; #endif #endif #endif `;de.IncludesShadersStoreWGSL[AGe]=bGe;const CGe={name:AGe,shader:bGe},vAt=Object.freeze(Object.defineProperty({__proto__:null,lightUboDeclarationWGSL:CGe},Symbol.toStringTag,{value:"Module"})),SGe="lightsFragmentFunctions",EGe=`struct lightingInfo {diffuse: vec3f, #ifdef SPECULARTERM specular: vec3f, #endif #ifdef NDOTL ndl: f32, #endif };fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.) {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} else {lightVectorW=normalize(-lightData.xyz);} var ndl: f32=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} fn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) {cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} result.diffuse=vec3f(0.); #ifdef SPECULARTERM result.specular=vec3f(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} fn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5; #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=mix(groundColor,diffuseColor,ndl); #ifdef SPECULARTERM var angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; #endif return result;} fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}`;de.IncludesShadersStoreWGSL[SGe]=EGe;const TGe={name:SGe,shader:EGe},yAt=Object.freeze(Object.defineProperty({__proto__:null,lightsFragmentFunctionsWGSL:TGe},Symbol.toStringTag,{value:"Module"})),MGe="shadowsFragmentFunctions",RGe=`#ifdef SHADOWS #ifndef SHADOWFLOAT fn unpack(color: vec4f)->f32 {const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} #endif fn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32 {var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} fn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); #else var shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; #endif return select(darkness,1.0,depth>shadow);} fn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0); #ifndef SHADOWFLOAT if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); #else var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; #endif var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;} fn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); #else var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; #endif var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} fn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer)); #else var shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x; #endif return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );} fn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); #else var shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; #endif return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}} fn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760); #ifndef SHADOWFLOAT if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); #else var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; #endif var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} fn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); #else var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; #endif var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} fn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32 { #ifdef IS_NDC_HALF_ZRANGE return clipSpace.z; #else return uvDepth.z; #endif } const GREATEST_LESS_THAN_ONE: f32=0.99999994; #define DISABLE_UNIFORMITY_ANALYSIS fn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} fn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} fn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} fn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32 {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} fn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} fn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} const PoissonSamplers32: array=array ( vec3f(0.06407013,0.05409927,0.), vec3f(0.7366577,0.5789394,0.), vec3f(-0.6270542,-0.5320278,0.), vec3f(-0.4096107,0.8411095,0.), vec3f(0.6849564,-0.4990818,0.), vec3f(-0.874181,-0.04579735,0.), vec3f(0.9989998,0.0009880066,0.), vec3f(-0.004920578,-0.9151649,0.), vec3f(0.1805763,0.9747483,0.), vec3f(-0.2138451,0.2635818,0.), vec3f(0.109845,0.3884785,0.), vec3f(0.06876755,-0.3581074,0.), vec3f(0.374073,-0.7661266,0.), vec3f(0.3079132,-0.1216763,0.), vec3f(-0.3794335,-0.8271583,0.), vec3f(-0.203878,-0.07715034,0.), vec3f(0.5912697,0.1469799,0.), vec3f(-0.88069,0.3031784,0.), vec3f(0.5040108,0.8283722,0.), vec3f(-0.5844124,0.5494877,0.), vec3f(0.6017799,-0.1726654,0.), vec3f(-0.5554981,0.1559997,0.), vec3f(-0.3016369,-0.3900928,0.), vec3f(-0.5550632,-0.1723762,0.), vec3f(0.925029,0.2995041,0.), vec3f(-0.2473137,0.5538505,0.), vec3f(0.9183037,-0.2862392,0.), vec3f(0.2469421,0.6718712,0.), vec3f(0.3916397,-0.4328209,0.), vec3f(-0.03576927,-0.6220032,0.), vec3f(-0.04661255,0.7995201,0.), vec3f(0.4402924,0.3640312,0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.) );const PoissonSamplers64: array=array ( vec3f(-0.613392,0.617481,0.), vec3f(0.170019,-0.040254,0.), vec3f(-0.299417,0.791925,0.), vec3f(0.645680,0.493210,0.), vec3f(-0.651784,0.717887,0.), vec3f(0.421003,0.027070,0.), vec3f(-0.817194,-0.271096,0.), vec3f(-0.705374,-0.668203,0.), vec3f(0.977050,-0.108615,0.), vec3f(0.063326,0.142369,0.), vec3f(0.203528,0.214331,0.), vec3f(-0.667531,0.326090,0.), vec3f(-0.098422,-0.295755,0.), vec3f(-0.885922,0.215369,0.), vec3f(0.566637,0.605213,0.), vec3f(0.039766,-0.396100,0.), vec3f(0.751946,0.453352,0.), vec3f(0.078707,-0.715323,0.), vec3f(-0.075838,-0.529344,0.), vec3f(0.724479,-0.580798,0.), vec3f(0.222999,-0.215125,0.), vec3f(-0.467574,-0.405438,0.), vec3f(-0.248268,-0.814753,0.), vec3f(0.354411,-0.887570,0.), vec3f(0.175817,0.382366,0.), vec3f(0.487472,-0.063082,0.), vec3f(-0.084078,0.898312,0.), vec3f(0.488876,-0.783441,0.), vec3f(0.470016,0.217933,0.), vec3f(-0.696890,-0.549791,0.), vec3f(-0.149693,0.605762,0.), vec3f(0.034211,0.979980,0.), vec3f(0.503098,-0.308878,0.), vec3f(-0.016205,-0.872921,0.), vec3f(0.385784,-0.393902,0.), vec3f(-0.146886,-0.859249,0.), vec3f(0.643361,0.164098,0.), vec3f(0.634388,-0.049471,0.), vec3f(-0.688894,0.007843,0.), vec3f(0.464034,-0.188818,0.), vec3f(-0.440840,0.137486,0.), vec3f(0.364483,0.511704,0.), vec3f(0.034028,0.325968,0.), vec3f(0.099094,-0.308023,0.), vec3f(0.693960,-0.366253,0.), vec3f(0.678884,-0.204688,0.), vec3f(0.001801,0.780328,0.), vec3f(0.145177,-0.898984,0.), vec3f(0.062655,-0.611866,0.), vec3f(0.315226,-0.604297,0.), vec3f(-0.780145,0.486251,0.), vec3f(-0.371868,0.882138,0.), vec3f(0.200476,0.494430,0.), vec3f(-0.494552,-0.711051,0.), vec3f(0.612476,0.705252,0.), vec3f(-0.578845,-0.768792,0.), vec3f(-0.772454,-0.090976,0.), vec3f(0.504440,0.372295,0.), vec3f(0.155736,0.065157,0.), vec3f(0.391522,0.849605,0.), vec3f(-0.620106,-0.328104,0.), vec3f(0.789239,-0.419965,0.), vec3f(-0.545396,0.538133,0.), vec3f(-0.178564,-0.596057,0.) );fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} fn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} fn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} fn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} fn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} fn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} #endif `;de.IncludesShadersStoreWGSL[MGe]=RGe;const IGe={name:MGe,shader:RGe},xAt=Object.freeze(Object.defineProperty({__proto__:null,shadowsFragmentFunctionsWGSL:IGe},Symbol.toStringTag,{value:"Module"})),PGe="imageProcessingFunctions",wGe=`#if TONEMAPPING==3 const PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peakvec3f {var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;} fn ACESFitted(color: vec3f)->vec3f {var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;} #endif #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS fn applyImageProcessing(result: vec4f)->vec4f { #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART var rgb=result.rgb;; #ifdef EXPOSURE rgb*=uniforms.exposureLinear; #endif #ifdef VIGNETTE var viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb; #ifdef VIGNETTEBLENDMODEMULTIPLY var vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier; #endif #ifdef VIGNETTEBLENDMODEOPAQUE rgb=mix(vignetteColor,rgb,vignette); #endif #endif #if TONEMAPPING==3 rgb=PBRNeutralToneMapping(rgb); #elif TONEMAPPING==2 rgb=ACESFitted(rgb); #elif TONEMAPPING==1 const tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb); #endif rgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb); #ifdef CONTRAST var resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);} #endif #ifdef COLORGRADING var colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy; #ifdef COLORGRADING3D var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb; #else var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb; #endif rgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www); #endif #ifdef COLORCURVES var luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a); #endif #ifdef DITHER var rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither)); #endif #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND return vec4f(rgb,result.a);}`;de.IncludesShadersStoreWGSL[PGe]=wGe;const DGe={name:PGe,shader:wGe},AAt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingFunctionsWGSL:DGe},Symbol.toStringTag,{value:"Module"})),LGe="fogFragmentDeclaration",OGe=`#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. #define FOGMODE_LINEAR 3. const E=2.71828;uniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32 {var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x) {fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} else if (FOGMODE_EXP==uniforms.vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDensity);} else if (FOGMODE_EXP2==uniforms.vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif `;de.IncludesShadersStoreWGSL[LGe]=OGe;const NGe={name:LGe,shader:OGe},bAt=Object.freeze(Object.defineProperty({__proto__:null,fogFragmentDeclarationWGSL:NGe},Symbol.toStringTag,{value:"Module"})),FGe="lightFragment",BGe=`#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else #ifdef PBR #ifdef SPOTLIGHT{X} preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,input.vPositionW); #elif defined(POINTLIGHT{X}) preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,input.vPositionW); #elif defined(HEMILIGHT{X}) preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(DIRLIGHT{X}) preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #endif preInfo.NdotV=NdotV; #ifdef SPOTLIGHT{X} #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #endif #elif defined(POINTLIGHT{X}) #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); #endif #else preInfo.attenuation=1.0; #endif #ifdef HEMILIGHT{X} preInfo.roughness=roughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif #ifdef IRIDESCENCE preInfo.iridescenceIntensity=iridescenceIntensity; #endif #ifdef HEMILIGHT{X} info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); #elif defined(SS_TRANSLUCENCY) info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); #else info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); #endif #ifdef SPECULARTERM #ifdef ANISOTROPIC info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); #else info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); #endif #endif #ifdef SHEEN #ifdef SHEEN_LINKWITHALBEDO preInfo.roughness=sheenOut.sheenIntensity; #else #ifdef HEMILIGHT{X} preInfo.roughness=sheenOut.sheenRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif #endif info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); #endif #ifdef CLEARCOAT #ifdef HEMILIGHT{X} preInfo.roughness=clearcoatOut.clearCoatRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); #ifdef CLEARCOAT_TINT absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; #ifdef SPECULARTERM info.specular*=absorption; #endif #endif info.diffuse*=info.clearCoat.w; #ifdef SPECULARTERM info.specular*=info.clearCoat.w; #endif #ifdef SHEEN info.sheen*=info.clearCoat.w; #endif #endif #else #ifdef SPOTLIGHT{X} info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); #elif defined(HEMILIGHT{X}) info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); #elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); #endif #endif #ifdef PROJECTEDLIGHTTEXTURE{X} info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},input.vPositionW); #endif #endif #ifdef SHADOW{X} #ifdef SHADOWCSMDEBUG{X} var shadowDebug{X}: vec3f; #endif #ifdef SHADOWCSM{X} #ifdef SHADOWCSMUSESHADOWMAXZ{X} var index{X}: i32=-1; #else var index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1; #endif var diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}} #ifdef SHADOWCSMUSESHADOWMAXZ{X} if (index{X}>=0) #endif { #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #else shadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #endif #else shadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}]; #endif #ifndef SHADOWCSMNOBLEND{X} var frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) {index{X}+=1;var nextShadow: f32=0.; #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else nextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #else nextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #endif #else nextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif shadow=mix(nextShadow,shadow,diffRatio); #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); #endif } #endif } #elif defined(SHADOWCLOSEESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithCloseESMCube(input.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithESMCube(input.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPOISSON{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithPoissonSamplingCube(input.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #else #if defined(SHADOWCUBE{X}) shadow=computeShadowCube(input.vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #endif #ifdef SHADOWONLY #ifndef SHADOWINUSE #define SHADOWINUSE #endif globalShadow+=shadow;shadowLightCount+=1.0; #endif #else shadow=1.; #endif aggShadow+=shadow;numLights+=1.0; #ifndef SHADOWONLY #ifdef CUSTOMUSERLIGHTING diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); #ifdef SPECULARTERM specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); #endif #elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) diffuseBase+=lightmapColor.rgb*shadow; #ifdef SPECULARTERM #ifndef LIGHTMAPNOSPECULAR{X} specularBase+=info.specular*shadow*lightmapColor.rgb; #endif #endif #ifdef CLEARCOAT #ifndef LIGHTMAPNOSPECULAR{X} clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; #endif #endif #ifdef SHEEN #ifndef LIGHTMAPNOSPECULAR{X} sheenBase+=info.sheen.rgb*shadow; #endif #endif #else #ifdef SHADOWCSMDEBUG{X} diffuseBase+=info.diffuse*shadowDebug{X}; #else diffuseBase+=info.diffuse*shadow; #endif #ifdef SPECULARTERM specularBase+=info.specular*shadow; #endif #ifdef CLEARCOAT clearCoatBase+=info.clearCoat.rgb*shadow; #endif #ifdef SHEEN sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif #endif `;de.IncludesShadersStoreWGSL[FGe]=BGe;const kGe={name:FGe,shader:BGe},CAt=Object.freeze(Object.defineProperty({__proto__:null,lightFragmentWGSL:kGe},Symbol.toStringTag,{value:"Module"})),SAt="logDepthFragment",EAt=`#ifdef LOGARITHMICDEPTH fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5; #endif `;de.IncludesShadersStoreWGSL[SAt]=EAt;const TAt="fogFragment",MAt=`#ifdef FOG var fog: f32=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a); #endif `;de.IncludesShadersStoreWGSL[TAt]=MAt;const UGe="backgroundPixelShader",zGe=`#include #include varying vPositionW: vec3f; #ifdef MAINUV1 varying vMainUV1: vec2f; #endif #ifdef MAINUV2 varying vMainUV2: vec2f; #endif #ifdef NORMAL varying vNormalW: vec3f; #endif #ifdef DIFFUSE #if DIFFUSEDIRECTUV==1 #define vDiffuseUV vMainUV1 #elif DIFFUSEDIRECTUV==2 #define vDiffuseUV vMainUV2 #else varying vDiffuseUV: vec2f; #endif var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #ifdef REFLECTION #ifdef REFLECTIONMAP_3D var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube; #ifdef TEXTURELODSUPPORT #else var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube; #endif #else var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d; #ifdef TEXTURELODSUPPORT #else var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d; #endif #endif #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #endif #include #endif #ifndef FROMLINEARSPACE #define FROMLINEARSPACE; #endif #ifndef SHADOWONLY #define SHADOWONLY; #endif #include #include[0..maxSimultaneousLights] #include #include #include #include #include #include #ifdef REFLECTIONFRESNEL #define FRESNEL_MAXIMUM_ON_ROUGH 0.25 fn fresnelSchlickEnvironmentGGX(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f {var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #ifdef PROJECTED_GROUND fn diskIntersectWithBackFaceCulling(ro: vec3f,rd: vec3f,c: vec3f,r: f32)->f32 {var d: f32=rd.y;if(d>0.0) { return 1e6; } var o: vec3f=ro-c;var t: f32=-o.y/d;var q: vec3f=o+rd*t;return select(1e6,t,(dot(q,q)f32 {var b: f32=dot(ro,rd);var c: f32=dot(ro,ro)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return -1.0; } h=sqrt(h);return-b+h;} fn project(viewDirectionW: vec3f,eyePosition: vec3f)->vec3f {var radius: f32=uniforms.projectedGroundInfos.x;var height: f32=uniforms.projectedGroundInfos.y;var camDir: vec3f=-viewDirectionW;var skySphereDistance: f32=sphereIntersect(eyePosition,camDir,radius);var skySpherePositionW: vec3f=eyePosition+camDir*skySphereDistance;var p: vec3f=normalize(skySpherePositionW);var upEyePosition=vec3f(eyePosition.x,eyePosition.y-height,eyePosition.z);var sIntersection: f32=sphereIntersect(upEyePosition,p,radius);var h: vec3f= vec3f(0.0,-height,0.0);var dIntersection: f32=diskIntersectWithBackFaceCulling(upEyePosition,p,h,radius);p=(upEyePosition+min(sIntersection,dIntersection)*p);return p;} #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW); #ifdef NORMAL var normalW: vec3f=normalize(fragmentInputs.vNormalW); #else var normalW: vec3f= vec3f(0.0,1.0,0.0); #endif var shadow: f32=1.;var globalShadow: f32=0.;var shadowLightCount: f32=0.;var aggShadow: f32=0.;var numLights: f32=0.; #include[0..maxSimultaneousLights] #ifdef SHADOWINUSE globalShadow/=shadowLightCount; #else globalShadow=1.0; #endif #ifndef BACKMAT_SHADOWONLY var reflectionColor: vec4f= vec4f(1.,1.,1.,1.); #ifdef REFLECTION #ifdef PROJECTED_GROUND var reflectionVector: vec3f=project(viewDirectionW,scene.vEyePosition.xyz);reflectionVector= (uniforms.reflectionMatrix*vec4f(reflectionVector,1.)).xyz; #else var reflectionVector: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW); #endif #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D var reflectionCoords: vec3f=reflectionVector; #else var reflectionCoords: vec2f=reflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION reflectionCoords/=reflectionVector.z; #endif reflectionCoords.y=1.0-reflectionCoords.y; #endif #ifdef REFLECTIONBLUR var reflectionLOD: f32=uniforms.vReflectionInfos.y; #ifdef TEXTURELODSUPPORT reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD); #else var lodReflectionNormalized: f32=saturate(reflectionLOD);var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var reflectionSpecularMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( textureSample(reflectionrHighSampler,reflectionrHighSamplerSampler,reflectionCoords), reflectionSpecularMid, lodReflectionNormalizedDoubled );} else {reflectionColor=mix( reflectionSpecularMid, textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords), lodReflectionNormalizedDoubled-1.0 );} #endif #else var reflectionSample: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);reflectionColor=reflectionSample; #endif #ifdef RGBDREFLECTION reflectionColor=vec4f(fromRGBD(reflectionColor).rgb,reflectionColor.a); #endif #ifdef GAMMAREFLECTION reflectionColor=vec4f(toLinearSpaceVec3(reflectionColor.rgb),reflectionColor.a); #endif #ifdef REFLECTIONBGR reflectionColor=vec4f(reflectionColor.bgr,reflectionColor.a); #endif reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a); #endif var diffuseColor: vec3f= vec3f(1.,1.,1.);var finalAlpha: f32=uniforms.alpha; #ifdef DIFFUSE var diffuseMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vDiffuseUV); #ifdef GAMMADIFFUSE diffuseMap=vec4f(toLinearSpaceVec3(diffuseMap.rgb),diffuseMap.a); #endif diffuseMap=vec4f(diffuseMap.rgb *uniforms.vDiffuseInfos.y,diffuseMap.a); #ifdef DIFFUSEHASALPHA finalAlpha*=diffuseMap.a; #endif diffuseColor=diffuseMap.rgb; #endif #ifdef REFLECTIONFRESNEL var colorBase: vec3f=diffuseColor; #else var colorBase: vec3f=reflectionColor.rgb*diffuseColor; #endif colorBase=max(colorBase,vec3f(0.0)); #ifdef USERGBCOLOR var finalColor: vec3f=colorBase; #else #ifdef USEHIGHLIGHTANDSHADOWCOLORS var mainColor: vec3f=mix(uniforms.vPrimaryColorShadow.rgb,uniforms.vPrimaryColor.rgb,colorBase); #else var mainColor: vec3f=uniforms.vPrimaryColor.rgb; #endif var finalColor: vec3f=colorBase*mainColor; #endif #ifdef REFLECTIONFRESNEL var reflectionAmount: vec3f=uniforms.vReflectionControl.xxx;var reflectionReflectance0: vec3f=uniforms.vReflectionControl.yyy;var reflectionReflectance90: vec3f=uniforms.vReflectionControl.zzz;var VdotN: f32=dot(normalize(scene.vEyePosition.xyz),normalW);var planarReflectionFresnel: vec3f=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; #ifdef REFLECTIONFALLOFF var reflectionDistanceFalloff: f32=1.0-saturate(length(vPositionW.xyz-uniforms.vBackgroundCenter)*uniforms.vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; #endif finalColor=mix(finalColor,reflectionColor.rgb,saturateVec3(reflectionAmount)); #endif #ifdef OPACITYFRESNEL var viewAngleToFloor: f32=dot(normalW,normalize(scene.vEyePosition.xyz-uniforms.vBackgroundCenter));const startAngle: f32=0.1;var fadeFactor: f32=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; #endif #ifdef SHADOWINUSE finalColor=mix(finalColor*uniforms.shadowLevel,finalColor,globalShadow); #endif var color: vec4f= vec4f(finalColor,finalAlpha); #else var color: vec4f= vec4f(uniforms.vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*uniforms.alpha); #endif #include #include #ifdef IMAGEPROCESSINGPOSTPROCESS #if !defined(SKIPFINALCOLORCLAMP) color=vec4f(clamp(color.rgb,vec3f(0.),vec3f(30.0)),color.a); #endif #else color=applyImageProcessing(color); #endif #ifdef PREMULTIPLYALPHA color=vec4f(color.rgb *color.a,color.a); #endif #ifdef NOISE color=vec4f(color.rgb+dither(fragmentInputs.vPositionW.xy,0.5),color.a);color=max(color,vec4f(0.0)); #endif fragmentOutputs.color=color; #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStoreWGSL[UGe]=zGe;const VGe={name:UGe,shader:zGe},RAt=Object.freeze(Object.defineProperty({__proto__:null,backgroundPixelShaderWGSL:VGe},Symbol.toStringTag,{value:"Module"})),IAt="backgroundVertexDeclaration",PAt=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; #endif #ifdef POINTSIZE uniform float pointSize; #endif `;de.IncludesShadersStore[IAt]=PAt;const wAt="backgroundUboDeclaration",DAt=`layout(std140,column_major) uniform;uniform Material {uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; #include `;de.IncludesShadersStore[wAt]=DAt;const LAt="fogVertexDeclaration",OAt=`#ifdef FOG varying vec3 vFogDistance; #endif `;de.IncludesShadersStore[LAt]=OAt;const GGe="lightVxFragmentDeclaration",WGe=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; #else vec4 vLightSpecular{X}=vec4(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #elif defined(SHADOWCUBE{X}) #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; #endif uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; #endif #ifdef SPOTLIGHT{X} uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; #elif defined(POINTLIGHT{X}) uniform vec4 vLightFalloff{X}; #elif defined(HEMILIGHT{X}) uniform vec3 vLightGround{X}; #endif #endif `;de.IncludesShadersStore[GGe]=WGe;const KGe={name:GGe,shader:WGe},NAt=Object.freeze(Object.defineProperty({__proto__:null,lightVxFragmentDeclaration:KGe},Symbol.toStringTag,{value:"Module"})),HGe="lightVxUboDeclaration",jGe=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} vec4 vLightDirection;vec4 vLightFalloff; #elif defined(POINTLIGHT{X}) vec4 vLightFalloff; #elif defined(HEMILIGHT{X}) vec3 vLightGround; #endif vec4 shadowsInfo;vec2 depthValues;} light{X}; #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #elif defined(SHADOWCUBE{X}) #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; #endif #endif #endif `;de.IncludesShadersStore[HGe]=jGe;const XGe={name:HGe,shader:jGe},FAt=Object.freeze(Object.defineProperty({__proto__:null,lightVxUboDeclaration:XGe},Symbol.toStringTag,{value:"Module"})),BAt="logDepthDeclaration",kAt=`#ifdef LOGARITHMICDEPTH uniform float logarithmicDepthConstant;varying float vFragmentDepth; #endif `;de.IncludesShadersStore[BAt]=kAt;const UAt="fogVertex",zAt=`#ifdef FOG vFogDistance=(view*worldPos).xyz; #endif `;de.IncludesShadersStore[UAt]=zAt;const YGe="shadowsVertex",QGe=`#ifdef SHADOWS #if defined(SHADOWCSM{X}) vPositionFromCamera{X}=view*worldPos;for (int i=0; i #include attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #include #include #include varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #ifdef MAINUV1 varying vec2 vMainUV1; #endif #ifdef MAINUV2 varying vec2 vMainUV2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 varying vec2 vDiffuseUV; #endif #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=position; #endif #include #include #include #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} #else gl_Position=viewProjection*finalWorld*vec4(position,1.0); #endif vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normal); #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); #ifdef EQUIRECTANGULAR_RELFECTION_FOV mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} #endif #endif #ifndef UV1 vec2 uv=vec2(0.,0.); #endif #ifndef UV2 vec2 uv2=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uv; #endif #ifdef MAINUV2 vMainUV2=uv2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 if (vDiffuseInfos.x==0.) {vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} else {vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} #endif #include #include #include[0..maxSimultaneousLights] #ifdef VERTEXCOLOR vColor=color; #endif #if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif #include #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStore[ZGe]=qGe;const JGe={name:ZGe,shader:qGe},KAt=Object.freeze(Object.defineProperty({__proto__:null,backgroundVertexShader:JGe},Symbol.toStringTag,{value:"Module"})),HAt="backgroundFragmentDeclaration",jAt=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; #ifdef USEHIGHLIGHTANDSHADOWCOLORS uniform vec4 vPrimaryColorShadow; #endif uniform float shadowLevel;uniform float alpha; #ifdef DIFFUSE uniform vec2 vDiffuseInfos; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; #endif #if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) uniform vec3 vBackgroundCenter; #endif #ifdef REFLECTIONFRESNEL uniform vec4 vReflectionControl; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) uniform mat4 view; #endif #ifdef PROJECTED_GROUND uniform vec2 projectedGroundInfos; #endif `;de.IncludesShadersStore[HAt]=jAt;const eWe="reflectionFunction",tWe=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) {float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) {float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) {vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);} vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix) {vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);} vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) {vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));} vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) {vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0)); #ifdef INVERTCUBICMAP coords.y*=-1.0; #endif return coords;} vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition) {vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0)); #ifdef INVERTCUBICMAP coords.y*=-1.0; #endif return coords;} vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix) {return vec3(reflectionMatrix*(view*worldPos));} vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix) {return vec3(reflectionMatrix*vec4(positionW,1.));} #ifdef REFLECTION vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal) { #ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); #endif #ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); #endif #ifdef REFLECTIONMAP_EQUIRECTANGULAR return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); #endif #ifdef REFLECTIONMAP_SPHERICAL return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix); #endif #ifdef REFLECTIONMAP_PLANAR return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); #endif #ifdef REFLECTIONMAP_CUBIC #ifdef USE_LOCAL_REFLECTIONMAP_CUBIC return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition); #else return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); #endif #endif #ifdef REFLECTIONMAP_PROJECTION return computeProjectionCoords(worldPos,view,reflectionMatrix); #endif #ifdef REFLECTIONMAP_SKYBOX return computeSkyBoxCoords(vPositionUVW,reflectionMatrix); #endif #ifdef REFLECTIONMAP_EXPLICIT return vec3(0,0,0); #endif } #endif `;de.IncludesShadersStore[eWe]=tWe;const iWe={name:eWe,shader:tWe},XAt=Object.freeze(Object.defineProperty({__proto__:null,reflectionFunction:iWe},Symbol.toStringTag,{value:"Module"})),rWe="imageProcessingDeclaration",sWe=`#ifdef EXPOSURE uniform float exposureLinear; #endif #ifdef CONTRAST uniform float contrast; #endif #if defined(VIGNETTE) || defined(DITHER) uniform vec2 vInverseScreenSize; #endif #ifdef VIGNETTE uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2; #endif #ifdef COLORCURVES uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive; #endif #ifdef COLORGRADING #ifdef COLORGRADING3D uniform highp sampler3D txColorTransform; #else uniform sampler2D txColorTransform; #endif uniform vec4 colorTransformSettings; #endif #ifdef DITHER uniform float ditherIntensity; #endif `;de.IncludesShadersStore[rWe]=sWe;const nWe={name:rWe,shader:sWe},YAt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingDeclaration:nWe},Symbol.toStringTag,{value:"Module"})),aWe="lightFragmentDeclaration",oWe=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; #else vec4 vLightSpecular{X}=vec4(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DArrayShadow shadowTexture{X}; #else uniform highp sampler2DArray shadowTexture{X}; #endif #ifdef SHADOWCSMDEBUG{X} const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] ( vec3 ( 1.5,0.0,0.0 ), vec3 ( 0.0,1.5,0.0 ), vec3 ( 0.0,0.0,5.5 ), vec3 ( 1.5,0.0,5.5 ), vec3 ( 1.5,1.5,0.0 ), vec3 ( 1.0,1.0,1.0 ), vec3 ( 0.0,1.0,5.5 ), vec3 ( 0.5,3.5,0.75 ) );vec3 shadowDebug{X}; #endif #ifdef SHADOWCSMUSESHADOWMAXZ{X} int index{X}=-1; #else int index{X}=SHADOWCSMNUM_CASCADES{X}-1; #endif float diff{X}=0.; #elif defined(SHADOWCUBE{X}) uniform samplerCube shadowTexture{X}; #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DShadow shadowTexture{X}; #else uniform sampler2D shadowTexture{X}; #endif uniform mat4 lightMatrix{X}; #endif uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; #endif #ifdef SPOTLIGHT{X} uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; #elif defined(POINTLIGHT{X}) uniform vec4 vLightFalloff{X}; #elif defined(HEMILIGHT{X}) uniform vec3 vLightGround{X}; #endif #ifdef PROJECTEDLIGHTTEXTURE{X} uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X}; #endif #endif `;de.IncludesShadersStore[aWe]=oWe;const lWe={name:aWe,shader:oWe},QAt=Object.freeze(Object.defineProperty({__proto__:null,lightFragmentDeclaration:lWe},Symbol.toStringTag,{value:"Module"})),cWe="lightUboDeclaration",uWe=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} vec4 vLightDirection;vec4 vLightFalloff; #elif defined(POINTLIGHT{X}) vec4 vLightFalloff; #elif defined(HEMILIGHT{X}) vec3 vLightGround; #endif vec4 shadowsInfo;vec2 depthValues;} light{X}; #ifdef PROJECTEDLIGHTTEXTURE{X} uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X}; #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DArrayShadow shadowTexture{X}; #else uniform highp sampler2DArray shadowTexture{X}; #endif #ifdef SHADOWCSMDEBUG{X} const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] ( vec3 ( 1.5,0.0,0.0 ), vec3 ( 0.0,1.5,0.0 ), vec3 ( 0.0,0.0,5.5 ), vec3 ( 1.5,0.0,5.5 ), vec3 ( 1.5,1.5,0.0 ), vec3 ( 1.0,1.0,1.0 ), vec3 ( 0.0,1.0,5.5 ), vec3 ( 0.5,3.5,0.75 ) );vec3 shadowDebug{X}; #endif #ifdef SHADOWCSMUSESHADOWMAXZ{X} int index{X}=-1; #else int index{X}=SHADOWCSMNUM_CASCADES{X}-1; #endif float diff{X}=0.; #elif defined(SHADOWCUBE{X}) uniform samplerCube shadowTexture{X}; #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DShadow shadowTexture{X}; #else uniform sampler2D shadowTexture{X}; #endif uniform mat4 lightMatrix{X}; #endif #endif #endif `;de.IncludesShadersStore[cWe]=uWe;const hWe={name:cWe,shader:uWe},$At=Object.freeze(Object.defineProperty({__proto__:null,lightUboDeclaration:hWe},Symbol.toStringTag,{value:"Module"})),dWe="lightsFragmentFunctions",fWe=`struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; #endif #ifdef NDOTL float ndl; #endif };lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) {vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} else {lightVectorW=normalize(-lightData.xyz);} float ndl=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) {cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} result.diffuse=vec3(0.); #ifdef SPECULARTERM result.specular=vec3(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=mix(groundColor,diffuseColor,ndl); #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; #endif return result;} #define inline vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;de.IncludesShadersStore[dWe]=fWe;const pWe={name:dWe,shader:fWe},ZAt=Object.freeze(Object.defineProperty({__proto__:null,lightsFragmentFunctions:pWe},Symbol.toStringTag,{value:"Module"})),mWe="shadowsFragmentFunctions",gWe=`#ifdef SHADOWS #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif #ifndef SHADOWFLOAT float unpack(vec4 color) {const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} #endif float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) {float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} #define inline float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) {vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT float shadow=unpack(textureCube(shadowSampler,directionToLight)); #else float shadow=textureCube(shadowSampler,directionToLight).x; #endif return depth>shadow ? darkness : 1.0;} #define inline float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) {vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); #ifndef SHADOWFLOAT if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} #endif #define inline float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} #define inline float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); #ifndef SHADOWFLOAT if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} #ifdef IS_NDC_HALF_ZRANGE #define ZINCLIP clipSpace.z #else #define ZINCLIP uvDepth.z #endif #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define GREATEST_LESS_THAN_ONE 0.99999994 #define DISABLE_UNIFORMITY_ANALYSIS #define inline float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} const vec3 PoissonSamplers32[64]=vec3[64]( vec3(0.06407013,0.05409927,0.), vec3(0.7366577,0.5789394,0.), vec3(-0.6270542,-0.5320278,0.), vec3(-0.4096107,0.8411095,0.), vec3(0.6849564,-0.4990818,0.), vec3(-0.874181,-0.04579735,0.), vec3(0.9989998,0.0009880066,0.), vec3(-0.004920578,-0.9151649,0.), vec3(0.1805763,0.9747483,0.), vec3(-0.2138451,0.2635818,0.), vec3(0.109845,0.3884785,0.), vec3(0.06876755,-0.3581074,0.), vec3(0.374073,-0.7661266,0.), vec3(0.3079132,-0.1216763,0.), vec3(-0.3794335,-0.8271583,0.), vec3(-0.203878,-0.07715034,0.), vec3(0.5912697,0.1469799,0.), vec3(-0.88069,0.3031784,0.), vec3(0.5040108,0.8283722,0.), vec3(-0.5844124,0.5494877,0.), vec3(0.6017799,-0.1726654,0.), vec3(-0.5554981,0.1559997,0.), vec3(-0.3016369,-0.3900928,0.), vec3(-0.5550632,-0.1723762,0.), vec3(0.925029,0.2995041,0.), vec3(-0.2473137,0.5538505,0.), vec3(0.9183037,-0.2862392,0.), vec3(0.2469421,0.6718712,0.), vec3(0.3916397,-0.4328209,0.), vec3(-0.03576927,-0.6220032,0.), vec3(-0.04661255,0.7995201,0.), vec3(0.4402924,0.3640312,0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.) );const vec3 PoissonSamplers64[64]=vec3[64]( vec3(-0.613392,0.617481,0.), vec3(0.170019,-0.040254,0.), vec3(-0.299417,0.791925,0.), vec3(0.645680,0.493210,0.), vec3(-0.651784,0.717887,0.), vec3(0.421003,0.027070,0.), vec3(-0.817194,-0.271096,0.), vec3(-0.705374,-0.668203,0.), vec3(0.977050,-0.108615,0.), vec3(0.063326,0.142369,0.), vec3(0.203528,0.214331,0.), vec3(-0.667531,0.326090,0.), vec3(-0.098422,-0.295755,0.), vec3(-0.885922,0.215369,0.), vec3(0.566637,0.605213,0.), vec3(0.039766,-0.396100,0.), vec3(0.751946,0.453352,0.), vec3(0.078707,-0.715323,0.), vec3(-0.075838,-0.529344,0.), vec3(0.724479,-0.580798,0.), vec3(0.222999,-0.215125,0.), vec3(-0.467574,-0.405438,0.), vec3(-0.248268,-0.814753,0.), vec3(0.354411,-0.887570,0.), vec3(0.175817,0.382366,0.), vec3(0.487472,-0.063082,0.), vec3(-0.084078,0.898312,0.), vec3(0.488876,-0.783441,0.), vec3(0.470016,0.217933,0.), vec3(-0.696890,-0.549791,0.), vec3(-0.149693,0.605762,0.), vec3(0.034211,0.979980,0.), vec3(0.503098,-0.308878,0.), vec3(-0.016205,-0.872921,0.), vec3(0.385784,-0.393902,0.), vec3(-0.146886,-0.859249,0.), vec3(0.643361,0.164098,0.), vec3(0.634388,-0.049471,0.), vec3(-0.688894,0.007843,0.), vec3(0.464034,-0.188818,0.), vec3(-0.440840,0.137486,0.), vec3(0.364483,0.511704,0.), vec3(0.034028,0.325968,0.), vec3(0.099094,-0.308023,0.), vec3(0.693960,-0.366253,0.), vec3(0.678884,-0.204688,0.), vec3(0.001801,0.780328,0.), vec3(0.145177,-0.898984,0.), vec3(0.062655,-0.611866,0.), vec3(0.315226,-0.604297,0.), vec3(-0.780145,0.486251,0.), vec3(-0.371868,0.882138,0.), vec3(0.200476,0.494430,0.), vec3(-0.494552,-0.711051,0.), vec3(0.612476,0.705252,0.), vec3(-0.578845,-0.768792,0.), vec3(-0.772454,-0.090976,0.), vec3(0.504440,0.372295,0.), vec3(0.155736,0.065157,0.), vec3(0.391522,0.849605,0.), vec3(-0.620106,-0.328104,0.), vec3(0.789239,-0.419965,0.), vec3(-0.545396,0.538133,0.), vec3(-0.178564,-0.596057,0.) ); #define inline float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i=0.) {index{X}=i;break;}} #ifdef SHADOWCSMUSESHADOWMAXZ{X} if (index{X}>=0) #endif { #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #else shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #endif #else shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; #endif #ifndef SHADOWCSMNOBLEND{X} float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) {index{X}+=1;float nextShadow=0.; #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #else nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #endif #else nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif shadow=mix(nextShadow,shadow,diffRatio); #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); #endif } #endif } #elif defined(SHADOWCLOSEESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPOISSON{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #else #if defined(SHADOWCUBE{X}) shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #endif #ifdef SHADOWONLY #ifndef SHADOWINUSE #define SHADOWINUSE #endif globalShadow+=shadow;shadowLightCount+=1.0; #endif #else shadow=1.; #endif aggShadow+=shadow;numLights+=1.0; #ifndef SHADOWONLY #ifdef CUSTOMUSERLIGHTING diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); #ifdef SPECULARTERM specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); #endif #elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) diffuseBase+=lightmapColor.rgb*shadow; #ifdef SPECULARTERM #ifndef LIGHTMAPNOSPECULAR{X} specularBase+=info.specular*shadow*lightmapColor.rgb; #endif #endif #ifdef CLEARCOAT #ifndef LIGHTMAPNOSPECULAR{X} clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; #endif #endif #ifdef SHEEN #ifndef LIGHTMAPNOSPECULAR{X} sheenBase+=info.sheen.rgb*shadow; #endif #endif #else #ifdef SHADOWCSMDEBUG{X} diffuseBase+=info.diffuse*shadowDebug{X}; #else diffuseBase+=info.diffuse*shadow; #endif #ifdef SPECULARTERM specularBase+=info.specular*shadow; #endif #ifdef CLEARCOAT clearCoatBase+=info.clearCoat.rgb*shadow; #endif #ifdef SHEEN sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif #endif `;de.IncludesShadersStore[SWe]=EWe;const TWe={name:SWe,shader:EWe},tbt=Object.freeze(Object.defineProperty({__proto__:null,lightFragment:TWe},Symbol.toStringTag,{value:"Module"})),ibt="logDepthFragment",rbt=`#ifdef LOGARITHMICDEPTH gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; #endif `;de.IncludesShadersStore[ibt]=rbt;const sbt="fogFragment",nbt=`#ifdef FOG float fog=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color.rgb=mix(vFogColor,color.rgb,fog); #endif `;de.IncludesShadersStore[sbt]=nbt;const MWe="backgroundPixelShader",RWe=`#ifdef TEXTURELODSUPPORT #extension GL_EXT_shader_texture_lod : enable #endif precision highp float; #include<__decl__backgroundFragment> #include varying vec3 vPositionW; #ifdef MAINUV1 varying vec2 vMainUV1; #endif #ifdef MAINUV2 varying vec2 vMainUV2; #endif #ifdef NORMAL varying vec3 vNormalW; #endif #ifdef DIFFUSE #if DIFFUSEDIRECTUV==1 #define vDiffuseUV vMainUV1 #elif DIFFUSEDIRECTUV==2 #define vDiffuseUV vMainUV2 #else varying vec2 vDiffuseUV; #endif uniform sampler2D diffuseSampler; #endif #ifdef REFLECTION #ifdef REFLECTIONMAP_3D #define sampleReflection(s,c) textureCube(s,c) uniform samplerCube reflectionSampler; #ifdef TEXTURELODSUPPORT #define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) #else uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; #endif #else #define sampleReflection(s,c) texture2D(s,c) uniform sampler2D reflectionSampler; #ifdef TEXTURELODSUPPORT #define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) #else uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; #endif #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #include #endif #ifndef FROMLINEARSPACE #define FROMLINEARSPACE; #endif #ifndef SHADOWONLY #define SHADOWONLY; #endif #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include #include #include #ifdef REFLECTIONFRESNEL #define FRESNEL_MAXIMUM_ON_ROUGH 0.25 vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) {float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #ifdef PROJECTED_GROUND float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q) vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=vec3(0.0,1.0,0.0); #endif float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; #include[0..maxSimultaneousLights] #ifdef SHADOWINUSE globalShadow/=shadowLightCount; #else globalShadow=1.0; #endif #ifndef BACKMAT_SHADOWONLY vec4 reflectionColor=vec4(1.,1.,1.,1.); #ifdef REFLECTION #ifdef PROJECTED_GROUND vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); #else vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #endif #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D vec3 reflectionCoords=reflectionVector; #else vec2 reflectionCoords=reflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION reflectionCoords/=reflectionVector.z; #endif reflectionCoords.y=1.0-reflectionCoords.y; #endif #ifdef REFLECTIONBLUR float reflectionLOD=vReflectionInfos.y; #ifdef TEXTURELODSUPPORT reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); #else float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( sampleReflection(reflectionSamplerHigh,reflectionCoords), reflectionSpecularMid, lodReflectionNormalizedDoubled );} else {reflectionColor=mix( reflectionSpecularMid, sampleReflection(reflectionSamplerLow,reflectionCoords), lodReflectionNormalizedDoubled-1.0 );} #endif #else vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; #endif #ifdef RGBDREFLECTION reflectionColor.rgb=fromRGBD(reflectionColor); #endif #ifdef GAMMAREFLECTION reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); #endif #ifdef REFLECTIONBGR reflectionColor.rgb=reflectionColor.bgr; #endif reflectionColor.rgb*=vReflectionInfos.x; #endif vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; #ifdef DIFFUSE vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); #ifdef GAMMADIFFUSE diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); #endif diffuseMap.rgb*=vDiffuseInfos.y; #ifdef DIFFUSEHASALPHA finalAlpha*=diffuseMap.a; #endif diffuseColor=diffuseMap.rgb; #endif #ifdef REFLECTIONFRESNEL vec3 colorBase=diffuseColor; #else vec3 colorBase=reflectionColor.rgb*diffuseColor; #endif colorBase=max(colorBase,0.0); #ifdef USERGBCOLOR vec3 finalColor=colorBase; #else #ifdef USEHIGHLIGHTANDSHADOWCOLORS vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); #else vec3 mainColor=vPrimaryColor.rgb; #endif vec3 finalColor=colorBase*mainColor; #endif #ifdef REFLECTIONFRESNEL vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; #ifdef REFLECTIONFALLOFF float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; #endif finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); #endif #ifdef OPACITYFRESNEL float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; #endif #ifdef SHADOWINUSE finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); #endif vec4 color=vec4(finalColor,finalAlpha); #else vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); #endif #include #include #ifdef IMAGEPROCESSINGPOSTPROCESS #if !defined(SKIPFINALCOLORCLAMP) color.rgb=clamp(color.rgb,0.,30.0); #endif #else color=applyImageProcessing(color); #endif #ifdef PREMULTIPLYALPHA color.rgb*=color.a; #endif #ifdef NOISE color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); #endif gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStore[MWe]=RWe;const IWe={name:MWe,shader:RWe},abt=Object.freeze(Object.defineProperty({__proto__:null,backgroundPixelShader:IWe},Symbol.toStringTag,{value:"Module"}));class Wk{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,Ge.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=e.bias===void 0?0:e.bias,this.power=e.power===void 0?1:e.power,this.leftColor=e.leftColor||Re.White(),this.rightColor=e.rightColor||Re.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new Wk;return Nl.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new Wk({isEnabled:e.isEnabled,leftColor:Re.FromArray(e.leftColor),rightColor:Re.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}qe._FresnelParametersParser=Wk.Parse;class wn{}wn.BindSceneUniformBuffer=$w;wn.PrepareDefinesForMergedUV=rn;wn.BindTextureMatrix=sn;wn.GetFogState=wJ;wn.PrepareDefinesForMisc=Kc;wn.PrepareDefinesForCamera=NJ;wn.PrepareDefinesForFrameBoundValues=Hc;wn.PrepareDefinesForBones=DJ;wn.PrepareDefinesForMorphTargets=LJ;wn.PrepareDefinesForBakedVertexAnimation=Cge;wn.PrepareDefinesForAttributes=Na;wn.PrepareDefinesForMultiview=qw;wn.PrepareDefinesForOIT=OJ;wn.PrepareDefinesForPrePass=mz;wn.PrepareDefinesForLight=pz;wn.PrepareDefinesForLights=du;wn.PrepareUniformsAndSamplersForLight=gz;wn.PrepareUniformsAndSamplersList=po;wn.HandleFallbacksForShadows=Zo;wn.PrepareAttributesForMorphTargetsInfluencers=rT;wn.PrepareAttributesForMorphTargets=dz;wn.PrepareAttributesForBakedVertexAnimation=Zw;wn.PrepareAttributesForBones=Vu;wn.PrepareAttributesForInstances=Ya;wn.PushAttributesForInstances=A_;wn.BindLightProperties=P9e;wn.BindLight=fz;wn.BindLights=hu;wn.BindFogParameters=ml;wn.BindBonesParameters=ql;wn.BindMorphTargetParameters=I0;wn.BindLogDepth=uo;const PWe="colorPixelShader",wWe=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) #define VERTEXCOLOR varying vec4 vColor; #else uniform vec4 color; #endif #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) gl_FragColor=vColor; #else gl_FragColor=color; #endif #include(color,gl_FragColor) #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[PWe]=wWe;const DWe={name:PWe,shader:wWe},obt=Object.freeze(Object.defineProperty({__proto__:null,colorPixelShader:DWe},Symbol.toStringTag,{value:"Module"})),lbt="vertexColorMixing",cbt=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) vColor=vec4(1.0); #ifdef VERTEXCOLOR #ifdef VERTEXALPHA vColor*=color; #else vColor.rgb*=color.rgb; #endif #endif #ifdef INSTANCESCOLOR vColor*=instanceColor; #endif #endif `;de.IncludesShadersStore[lbt]=cbt;const LWe="colorVertexShader",OWe=`attribute vec3 position; #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #ifdef FOG uniform mat4 view; #endif #include uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN #include #include #include vec4 worldPos=finalWorld*vec4(position,1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[LWe]=OWe;const NWe={name:LWe,shader:OWe},ubt=Object.freeze(Object.defineProperty({__proto__:null,colorVertexShader:NWe},Symbol.toStringTag,{value:"Module"}));class hbt extends na{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Ze(0,0,0,1))}}class Gu extends Pr{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Re(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}F([X(),Fe("_markAllSubMeshesAsLightsDirty")],Gu.prototype,"maxSimultaneousLights",void 0);F([X(),Fe("_markAllSubMeshesAsLightsDirty")],Gu.prototype,"disableLighting",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Gu.prototype,"environmentTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Gu.prototype,"invertNormalMapX",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Gu.prototype,"invertNormalMapY",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Gu.prototype,"normalTexture",void 0);F([br("emissive"),Fe("_markAllSubMeshesAsTexturesDirty")],Gu.prototype,"emissiveColor",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty")],Gu.prototype,"emissiveTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Gu.prototype,"occlusionStrength",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Gu.prototype,"occlusionTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Gu.prototype,"alphaCutOff",void 0);F([X()],Gu.prototype,"doubleSided",null);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty",null)],Gu.prototype,"lightmapTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Gu.prototype,"useLightmapAsShadowmap",void 0);class h_ extends Gu{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=qe.Clone(()=>new h_(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=qe.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=qe.Parse(()=>new h_(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}F([br(),Fe("_markAllSubMeshesAsTexturesDirty","_albedoColor")],h_.prototype,"baseColor",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],h_.prototype,"baseTexture",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],h_.prototype,"metallic",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],h_.prototype,"roughness",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],h_.prototype,"metallicRoughnessTexture",void 0);ve("BABYLON.PBRMetallicRoughnessMaterial",h_);class d_ extends Gu{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=qe.Clone(()=>new d_(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=qe.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=qe.Parse(()=>new d_(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}F([br("diffuse"),Fe("_markAllSubMeshesAsTexturesDirty","_albedoColor")],d_.prototype,"diffuseColor",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],d_.prototype,"diffuseTexture",void 0);F([br("specular"),Fe("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],d_.prototype,"specularColor",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty","_microSurface")],d_.prototype,"glossiness",void 0);F([ii(),Fe("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],d_.prototype,"specularGlossinessTexture",void 0);ve("BABYLON.PBRSpecularGlossinessMaterial",d_);const dbt="pbrUboDeclaration",fbt=`uniform vAlbedoInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionColor: vec3f;uniform vAlbedoColor: vec4f;uniform vLightingIntensity: vec4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f; #define ADDITIONAL_UBO_DECLARATION #include #include `;de.IncludesShadersStoreWGSL[dbt]=fbt;const pbt="uvAttributeDeclaration",mbt=`#ifdef UV{X} attribute uv{X}: vec2f; #endif `;de.IncludesShadersStoreWGSL[pbt]=mbt;const gbt="mainUVVaryingDeclaration",_bt=`#ifdef MAINUV{X} varying vMainUV{X}: vec2f; #endif `;de.IncludesShadersStoreWGSL[gbt]=_bt;const vbt="prePassVertexDeclaration",ybt=`#ifdef PREPASS #ifdef PREPASS_DEPTH varying vViewPos: vec3f; #endif #ifdef PREPASS_VELOCITY uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif `;de.IncludesShadersStoreWGSL[vbt]=ybt;const xbt="samplerVertexDeclaration",Abt=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying v_VARYINGNAME_UV: vec2f; #endif `;de.IncludesShadersStoreWGSL[xbt]=Abt;const bbt="harmonicsFunctions",Cbt=`#ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00 + uniforms.vSphericalL1_1*(normal.y) + uniforms.vSphericalL10*(normal.z) + uniforms.vSphericalL11*(normal.x) + uniforms.vSphericalL2_2*(normal.y*normal.x) + uniforms.vSphericalL2_1*(normal.y*normal.z) + uniforms.vSphericalL20*((3.0*normal.z*normal.z)-1.0) + uniforms.vSphericalL21*(normal.z*normal.x) + uniforms.vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} #else fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;} #endif #endif `;de.IncludesShadersStoreWGSL[bbt]=Cbt;const Sbt="bumpVertexDeclaration",Ebt=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif #endif `;de.IncludesShadersStoreWGSL[Sbt]=Ebt;const Tbt="prePassVertex",Mbt=`#ifdef PREPASS_DEPTH vertexOutputs.vViewPos=(scene.view*worldPos).rgb; #endif #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*worldPos; #if NUM_BONE_INFLUENCERS>0 var previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0); #else vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #endif `;de.IncludesShadersStoreWGSL[Tbt]=Mbt;const Rbt="uvVariableDeclaration",Ibt=`#ifdef MAINUV{X} #if !defined(UV{X}) var uv{X}: vec2f=vec2f(0.,0.); #else var uv{X}: vec2f=vertexInputs.uv{X}; #endif vertexOutputs.vMainUV{X}=uv{X}; #endif `;de.IncludesShadersStoreWGSL[Rbt]=Ibt;const Pbt="samplerVertexImplementation",wbt=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (uniforms.v_INFONAME_==0.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;} #ifdef UV2 else if (uniforms.v_INFONAME_==1.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv2,1.0,0.0)).xy;} #endif #ifdef UV3 else if (uniforms.v_INFONAME_==2.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;} #endif #ifdef UV4 else if (uniforms.v_INFONAME_==3.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;} #endif #ifdef UV5 else if (uniforms.v_INFONAME_==4.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;} #endif #ifdef UV6 else if (uniforms.v_INFONAME_==5.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;} #endif #endif `;de.IncludesShadersStoreWGSL[Pbt]=wbt;const Dbt="bumpVertex",Lbt=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2]; #endif #endif `;de.IncludesShadersStoreWGSL[Dbt]=Lbt;const Obt="vertexColorMixing",Nbt=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) vertexOutputs.vColor=vec4f(1.0); #ifdef VERTEXCOLOR #ifdef VERTEXALPHA vertexOutputs.vColor*=vertexInputs.color; #else vertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*vertexInputs.color.rgb,vertexOutputs.vColor.a); #endif #endif #ifdef INSTANCESCOLOR vertexOutputs.vColor*=vertexInputs.instanceColor; #endif #endif `;de.IncludesShadersStoreWGSL[Obt]=Nbt;const FWe="pbrVertexShader",BWe=`#include #define CUSTOM_VERTEX_BEGIN attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif #ifdef TANGENT attribute tangent: vec4f; #endif #ifdef UV1 attribute uv: vec2f; #endif #include[2..7] #include[1..7] #ifdef VERTEXCOLOR attribute color: vec4f; #endif #include #include #include #include #include #include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) #endif #ifdef SUBSURFACE #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor) #endif varying vPositionW: vec3f; #if DEBUGMODE>0 varying vClipSpacePosition: vec4f; #endif #ifdef NORMAL varying vNormalW: vec3f; #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) varying vEnvironmentIrradiance: vec3f; #include #endif #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif #include #include #include #include[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var positionUpdated: vec3f=vertexInputs.position; #ifdef NORMAL var normalUpdated: vec3f=vertexInputs.normal; #endif #ifdef TANGENT var tangentUpdated: vec4f=vertexInputs.tangent; #endif #ifdef UV1 var uvUpdated: vec2f=vertexInputs.uv; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vertexOutputs.vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz; #include #ifdef NORMAL var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); #if defined(INSTANCES) && defined(THIN_INSTANCES) vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); #endif #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz; #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;} #else vertexOutputs.position=scene.viewProjection*worldPos; #endif #if DEBUGMODE>0 vertexOutputs.vClipSpacePosition=vertexOutputs.position; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz); #endif #ifndef UV1 var uvUpdated: vec2f= vec2f(0.,0.); #endif #ifdef MAINUV1 vertexOutputs.vMainUV1=uvUpdated; #endif #include[2..7] #include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z) #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) #endif #ifdef SUBSURFACE #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) #include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x) #endif #include #include #include #include[0..maxSimultaneousLights] #include #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[FWe]=BWe;const kWe={name:FWe,shader:BWe},UWe=Object.freeze(Object.defineProperty({__proto__:null,pbrVertexShaderWGSL:kWe},Symbol.toStringTag,{value:"Module"})),Fbt="prePassDeclaration",Bbt=`#ifdef PREPASS #ifdef PREPASS_DEPTH varying vViewPos: vec3f; #endif #ifdef PREPASS_VELOCITY varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif `;de.IncludesShadersStoreWGSL[Fbt]=Bbt;const kbt="oitDeclaration",Ubt=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY #define MAX_DEPTH 99999.0 var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d; #endif `;de.IncludesShadersStoreWGSL[kbt]=Ubt;const zbt="pbrFragmentExtraDeclaration",Vbt=`varying vPositionW: vec3f; #if DEBUGMODE>0 varying vClipSpacePosition: vec4f; #endif #include[1..7] #ifdef NORMAL varying vNormalW: vec3f; #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) varying vEnvironmentIrradiance: vec3f; #endif #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif `;de.IncludesShadersStoreWGSL[zbt]=Vbt;const Gbt="samplerFragmentDeclaration",Wbt=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 #define v_VARYINGNAME_UV vMainUV2 #elif _DEFINENAME_DIRECTUV==3 #define v_VARYINGNAME_UV vMainUV3 #elif _DEFINENAME_DIRECTUV==4 #define v_VARYINGNAME_UV vMainUV4 #elif _DEFINENAME_DIRECTUV==5 #define v_VARYINGNAME_UV vMainUV5 #elif _DEFINENAME_DIRECTUV==6 #define v_VARYINGNAME_UV vMainUV6 #else varying v_VARYINGNAME_UV: vec2f; #endif var _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d; #endif `;de.IncludesShadersStoreWGSL[Gbt]=Wbt;const Kbt="samplerFragmentAlternateDeclaration",Hbt=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 #define v_VARYINGNAME_UV vMainUV2 #elif _DEFINENAME_DIRECTUV==3 #define v_VARYINGNAME_UV vMainUV3 #elif _DEFINENAME_DIRECTUV==4 #define v_VARYINGNAME_UV vMainUV4 #elif _DEFINENAME_DIRECTUV==5 #define v_VARYINGNAME_UV vMainUV5 #elif _DEFINENAME_DIRECTUV==6 #define v_VARYINGNAME_UV vMainUV6 #else varying v_VARYINGNAME_UV: vec2f; #endif #endif `;de.IncludesShadersStoreWGSL[Kbt]=Hbt;const jbt="pbrFragmentSamplersDeclaration",Xbt=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) var clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d; #endif #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) var sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d; #endif #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) #endif #ifdef REFLECTION #ifdef REFLECTIONMAP_3D var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube; #ifdef LODBASEDMICROSFURACE #else var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube; #endif #ifdef USEIRRADIANCEMAP var irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube; #endif #else var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d; #ifdef LODBASEDMICROSFURACE #else var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d; #endif #ifdef USEIRRADIANCEMAP var irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d; #endif #endif #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #endif #endif #ifdef ENVIRONMENTBRDF var environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d; #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION #ifdef SS_REFRACTIONMAP_3D var refractionSamplerSampler: sampler;var refractionSampler: texture_cube; #ifdef LODBASEDMICROSFURACE #else var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube; #endif #else var refractionSamplerSampler: sampler;var refractionSampler: texture_2d; #ifdef LODBASEDMICROSFURACE #else var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d; #endif #endif #endif #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor) #endif `;de.IncludesShadersStoreWGSL[jbt]=Xbt;const Ybt="subSurfaceScatteringFunctions",Qbt=`fn testLightingForSSS(diffusionProfile: f32)->bool {return diffusionProfile<1.;}`;de.IncludesShadersStoreWGSL[Ybt]=Qbt;const $bt="importanceSampling",Zbt=`fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} fn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} fn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f { var phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;de.IncludesShadersStoreWGSL[$bt]=Zbt;const qbt="pbrHelperFunctions",Jbt=`#define MINIMUMVARIANCE 0.0005 fn convertRoughnessToAverageSlope(roughness: f32)->f32 {return roughness*roughness+MINIMUMVARIANCE;} fn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;} fn getAARoughnessFactors(normalVector: vec3f)->vec2f { #ifdef SPECULARAA var nDfdx: vec3f=dpdx(normalVector.xyz);var nDfdy: vec3f=dpdy(normalVector.xyz);var slopeSquare: f32=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));var geometricRoughnessFactor: f32=pow(saturate(slopeSquare),0.333);var geometricAlphaGFactor: f32=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2f(geometricRoughnessFactor,geometricAlphaGFactor); #else return vec2f(0.); #endif } #ifdef ANISOTROPIC #ifdef ANISOTROPIC_LEGACY fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);} fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var anisotropicFrameDirection: vec3f=select(T,B,anisotropy>=0.0);var anisotropicFrameTangent: vec3f=cross(normalize(anisotropicFrameDirection),V);var anisotropicFrameNormal: vec3f=cross(anisotropicFrameTangent,anisotropicFrameDirection);var anisotropicNormal: vec3f=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} #else fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG,MINIMUMVARIANCE);return vec2f(alphaT,alphaB);} fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var bentNormal: vec3f=cross(B,V);bentNormal=normalize(cross(bentNormal,B));var sq=1.0-anisotropy*(1.0-roughness);var a: f32=sq*sq*sq*sq;bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} #endif #endif #if defined(CLEARCOAT) || defined(SS_REFRACTION) fn cocaLambertVec3(alpha: vec3f,distance: f32)->vec3f {return exp(-alpha*distance);} fn cocaLambert(NdotVRefract: f32,NdotLRefract: f32,alpha: vec3f,thickness: f32)->vec3f {return cocaLambertVec3(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} fn computeColorAtDistanceInMedia(color: vec3f,distance: f32)->vec3f {return -log(color)/distance;} fn computeClearCoatAbsorption(NdotVRefract: f32,NdotLRefract: f32,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var clearCoatAbsorption: vec3f=mix( vec3f(1.0), cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), clearCoatIntensity);return clearCoatAbsorption;} #endif #ifdef MICROSURFACEAUTOMATIC fn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32 {const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;} #endif `;de.IncludesShadersStoreWGSL[qbt]=Jbt;const eCt="pbrDirectLightingSetupFunctions",tCt=`struct preLightingInfo {lightOffset: vec3f, lightDistanceSquared: f32, lightDistance: f32, attenuation: f32, L: vec3f, H: vec3f, NdotV: f32, NdotLUnclamped: f32, NdotL: f32, VdotH: f32, roughness: f32, #ifdef IRIDESCENCE iridescenceIntensity: f32 #endif };fn computePointAndSpotPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f,posW: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} fn computeDirectionalPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} fn computeHemisphericPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; #ifdef SPECULARTERM result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); #endif return result;}`;de.IncludesShadersStoreWGSL[eCt]=tCt;const iCt="pbrDirectLightingFalloffFunctions",rCt=`fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32 {return max(0.,1.0-length(lightOffset)/range);} fn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32 {return 1.0/maxEps(lightDistanceSquared);} fn computeDistanceLightFalloff_GLTF(lightDistanceSquared: f32,inverseSquaredRange: f32)->f32 {var lightDistanceFalloff: f32=1.0/maxEps(lightDistanceSquared);var factor: f32=lightDistanceSquared*inverseSquaredRange;var attenuation: f32=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} fn computeDistanceLightFalloff(lightOffset: vec3f,lightDistanceSquared: f32,range: f32,inverseSquaredRange: f32)->f32 { #ifdef USEPHYSICALLIGHTFALLOFF return computeDistanceLightFalloff_Physical(lightDistanceSquared); #elif defined(USEGLTFLIGHTFALLOFF) return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); #else return computeDistanceLightFalloff_Standard(lightOffset,range); #endif } fn computeDirectionalLightFalloff_Standard(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32)->f32 {var falloff: f32=0.0;var cosAngle: f32=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) {falloff=max(0.,pow(cosAngle,exponent));} return falloff;} fn computeDirectionalLightFalloff_Physical(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32)->f32 {const kMinusLog2ConeAngleIntensityRatio: f32=6.64385618977; var concentrationKappa: f32=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);var lightDirectionSpreadSG: vec4f= vec4f(-lightDirection*concentrationKappa,-concentrationKappa);var falloff: f32=exp2(dot( vec4f(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} fn computeDirectionalLightFalloff_GLTF(lightDirection: vec3f,directionToLightCenterW: vec3f,lightAngleScale: f32,lightAngleOffset: f32)->f32 {var cd: f32=dot(-lightDirection,directionToLightCenterW);var falloff: f32=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} fn computeDirectionalLightFalloff(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32,lightAngleScale: f32,lightAngleOffset: f32)->f32 { #ifdef USEPHYSICALLIGHTFALLOFF return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); #elif defined(USEGLTFLIGHTFALLOFF) return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); #else return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); #endif }`;de.IncludesShadersStoreWGSL[iCt]=rCt;const sCt="pbrBRDFFunctions",nCt=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 #ifdef MS_BRDF_ENERGY_CONSERVATION fn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} #endif #ifdef ENVIRONMENTBRDF fn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV); #ifdef ENVIRONMENTBRDF_RGBD brdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a); #endif return brdfLookup.rgb;} fn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f { #ifdef BRDF_V_HEIGHT_CORRELATED var reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; #else var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; #endif return reflectance;} fn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f { #ifdef BRDF_V_HEIGHT_CORRELATED var reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); #else var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; #endif return reflectance;} #endif /* NOT USED #if defined(SHEEN) && defined(SHEEN_SOFTER) fn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32 {var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} #endif */ #if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) fn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f {var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) /** * The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. * The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table */ fn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} #endif fn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} fn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32 {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} #ifdef CLEARCOAT fn getR0RemappedForClearCoat(f0: vec3f)->vec3f { #ifdef CLEARCOAT_DEFAULTIOR #ifdef MOBILE return saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256); #else return saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); #endif #else var s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t); #endif } #endif #ifdef IRIDESCENCE const XYZ_TO_REC709: mat3x3f= mat3x3f( 3.2404542,-0.9692660, 0.0556434, -1.5371385, 1.8760108,-0.2040259, -0.4985314, 0.0415560, 1.0572252 );fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} fn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));} fn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));} fn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var 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 vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;} fn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} var cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIORf32 {var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} #ifdef SHEEN fn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32 {var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} #endif #ifdef ANISOTROPIC fn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} #endif #ifdef BRDF_V_HEIGHT_CORRELATED fn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 { #ifdef MOBILE var GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); #else var a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); #endif } #else fn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32 { #ifdef MOBILE return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); #else var alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); #endif } fn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} #endif #ifdef ANISOTROPIC fn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;} #endif #ifdef CLEARCOAT fn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); } #endif #ifdef SHEEN fn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32 {return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} /* NOT USED #ifdef SHEEN_SOFTER fn l(x: f32,alphaG: f32)->f32 {var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} fn lambdaSheen(cosTheta: f32,alphaG: f32)->f32 {return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} fn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} #endif */ #endif fn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 = (1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * (1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} #ifdef SS_TRANSLUCENCY fn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} fn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);} #endif `;de.IncludesShadersStoreWGSL[sCt]=nCt;const aCt="hdrFilteringFunctions",oCt=`#ifdef NUM_SAMPLES #if NUM_SAMPLES>0 fn radicalInverse_VdC(value: u32)->f32 {var bits=(value<<16u) | (value>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10; } fn hammersley(i: u32,N: u32)->vec2f {return vec2f( f32(i)/ f32(N),radicalInverse_VdC(i));} fn log4(x: f32)->f32 {return log2(x)/2.;} const NUM_SAMPLES_FLOAT: f32= f32(NUM_SAMPLES);const NUM_SAMPLES_FLOAT_INVERSED: f32=1./NUM_SAMPLES_FLOAT;const K: f32=4.;fn irradiance(inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f {var n: vec3f=normalize(inputN);var result: vec3f= vec3f(0.0);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);for(var i: u32=0u; i0.) {var pdf_inversed: f32=PI/NoL;var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0,maxLevel);var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*Ls,mipLevel).rgb; #ifdef GAMMA_INPUT c=toLinearSpaceVec3(c); #endif result+=c;}} result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} fn radiance(alphaG: f32,inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f {var n: vec3f=normalize(inputN);var c: vec3f=textureSample(inputTexture,inputSampler,n).rgb; if (alphaG==0.) { #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif return c;} else {var result: vec3f= vec3f(0.);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var weight: f32=0.;for(var i: u32=0u; i0.) {var pdf_inversed: f32=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp( f32(l),0.0,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*L,mipLevel).rgb; #ifdef GAMMA_INPUT c=toLinearSpace(c); #endif result+=c*NoL;}} result=result/weight;return result;}} #endif #endif `;de.IncludesShadersStoreWGSL[aCt]=oCt;const lCt="pbrDirectLightingFunctions",cCt=`#define CLEARCOATREFLECTANCE90 1.0 struct lightingInfo {diffuse: vec3f, #ifdef SPECULARTERM specular: vec3f, #endif #ifdef CLEARCOAT clearCoat: vec4f, #endif #ifdef SHEEN sheen: vec3f #endif };fn adjustRoughnessFromLightProperties(roughness: f32,lightRadius: f32,lightDistance: f32)->f32 { #if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) var lightRoughness: f32=lightRadius/lightDistance;var totalRoughness: f32=saturate(lightRoughness+roughness);return totalRoughness; #else return roughness; #endif } fn computeHemisphericDiffuseLighting(info: preLightingInfo,lightColor: vec3f,groundColor: vec3f)->vec3f {return mix(groundColor,lightColor,info.NdotL);} fn computeDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {var diffuseTerm: f32=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f{var strq: vec4f=textureProjectionMatrix* vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return toLinearSpaceVec3(textureColor);} #ifdef SS_TRANSLUCENCY fn computeDiffuseAndTransmittedLighting(info: preLightingInfo,lightColor: vec3f,transmittance: vec3f)->vec3f {var NdotL: f32=absEps(info.NdotLUnclamped);var wrapNdotL: f32=computeWrappedDiffuseNdotL(NdotL,0.02);var trAdapt: f32=step(0.,info.NdotLUnclamped);var transmittanceNdotL: vec3f=mix(transmittance*wrapNdotL, vec3f(wrapNdotL),trAdapt);var diffuseTerm: f32=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} #endif #ifdef SPECULARTERM fn computeSpecularLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90); #ifdef IRIDESCENCE fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); #endif var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); #ifdef BRDF_V_HEIGHT_CORRELATED var smithVisibility: f32=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); #else var smithVisibility: f32=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); #endif var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} #endif #ifdef ANISOTROPIC fn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,vec2f(geometricRoughnessFactor*geometricRoughnessFactor));var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90); #ifdef IRIDESCENCE fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); #endif var distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} #endif #ifdef CLEARCOAT fn computeClearCoatLighting(info: preLightingInfo,Ncc: vec3f,geometricRoughnessFactor: f32,clearCoatIntensity: f32,lightColor: vec3f)->vec4f {var NccdotL: f32=saturateEps(dot(Ncc,info.L));var NccdotH: f32=saturateEps(dot(Ncc,info.H));var clearCoatRoughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);var fresnel: f32=fresnelSchlickGGX(info.VdotH,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);var kelemenVisibility: f32=visibility_Kelemen(info.VdotH);var clearCoatTerm: f32=fresnel*distribution*kelemenVisibility;return vec4f( clearCoatTerm*info.attenuation*NccdotL*lightColor, 1.0-fresnel );} fn computeClearCoatLightingAbsorption(NdotVRefract: f32,L: vec3f,Ncc: vec3f,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var LRefract: vec3f=-refract(L,Ncc,uniforms.vClearCoatRefractionParams.y);var NdotLRefract: f32=saturateEps(dot(Ncc,LRefract));var absorption: vec3f=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} #endif #ifdef SHEEN fn computeSheenLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: f32=1.;var distribution: f32=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER var visibility: f32=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); #else */ var visibility: f32=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ var sheenTerm: f32=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} #endif `;de.IncludesShadersStoreWGSL[lCt]=cCt;const uCt="pbrIBLFunctions",hCt=`#if defined(REFLECTION) || defined(SS_REFRACTION) fn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;} fn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;} #endif #if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) fn environmentRadianceOcclusion(ambientOcclusion: f32,NdotVUnclamped: f32)->f32 {var temp: f32=NdotVUnclamped+ambientOcclusion;return saturate(temp*temp-1.0+ambientOcclusion);} #endif #if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) fn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f)->f32 {var reflection: vec3f=reflect(view,normal);var temp: f32=saturate(1.0+1.1*dot(reflection,geometricNormal));return temp*temp;} #endif #if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) fn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;} fn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} #endif `;de.IncludesShadersStoreWGSL[uCt]=hCt;const zWe="bumpFragmentMainFunctions",VWe=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif #ifdef OBJECTSPACE_NORMALMAP uniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f {var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0]; var a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0]; var a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4( (a11*b11-a12*b10+a13*b09)/det, (a02*b10-a01*b11-a03*b09)/det, (a31*b05-a32*b04+a33*b03)/det, (a22*b04-a21*b05-a23*b03)/det, (a12*b08-a10*b11-a13*b07)/det, (a00*b11-a02*b08+a03*b07)/det, (a32*b02-a30*b05-a33*b01)/det, (a20*b05-a22*b02+a23*b01)/det, (a10*b10-a11*b08+a13*b06)/det, (a01*b08-a00*b10-a03*b06)/det, (a30*b04-a31*b02+a33*b00)/det, (a21*b02-a20*b04-a23*b00)/det, (a11*b07-a10*b09-a12*b06)/det, (a00*b09-a01*b07+a02*b06)/det, (a31*b01-a30*b03-a32*b00)/det, (a20*b03-a21*b01+a22*b00)/det);return mat4x4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], mi[0][1],mi[1][1],mi[2][1],mi[3][1], mi[0][2],mi[1][2],mi[2][2],mi[3][2], mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} #endif fn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f {var output=normal; #ifdef NORMALXYSCALE output=normalize(output* vec3f(scale,scale,1.0)); #endif return normalize(cotangentFrame*output);} fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f {return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f {var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);} #endif `;de.IncludesShadersStoreWGSL[zWe]=VWe;const GWe={name:zWe,shader:VWe},dCt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentMainFunctionsWGSL:GWe},Symbol.toStringTag,{value:"Module"})),WWe="bumpFragmentFunctions",KWe=`#if defined(BUMP) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) #endif #if defined(BUMP) && defined(PARALLAX) const minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight) {var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} else {currRayHeight-=stepSize;vLastOffset=vCurrOffset; #ifdef PARALLAX_RHS vCurrOffset-=stepSize*vMaxOffset; #else vCurrOffset+=stepSize*vMaxOffset; #endif lastSampledHeight=currSampledHeight;}} return vCurrOffset;} fn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f {var height: f32=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height; #ifdef PARALLAX_RHS return texCoordOffset; #else return -texCoordOffset; #endif } #endif `;de.IncludesShadersStoreWGSL[WWe]=KWe;const HWe={name:WWe,shader:KWe},fCt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentFunctionsWGSL:HWe},Symbol.toStringTag,{value:"Module"})),pCt="pbrBlockAlbedoOpacity",mCt=`struct albedoOpacityOutParams {surfaceAlbedo: vec3f, alpha: f32}; #define pbr_inline fn albedoOpacityBlock( vAlbedoColor: vec4f #ifdef ALBEDO ,albedoTexture: vec4f ,albedoInfos: vec2f #endif #ifdef OPACITY ,opacityMap: vec4f ,vOpacityInfos: vec2f #endif #ifdef DETAIL ,detailColor: vec4f ,vDetailInfos: vec4f #endif #ifdef DECAL ,decalColor: vec4f ,vDecalInfos: vec4f #endif )->albedoOpacityOutParams {var outParams: albedoOpacityOutParams;var surfaceAlbedo: vec3f=vAlbedoColor.rgb;var alpha: f32=vAlbedoColor.a; #ifdef ALBEDO #if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) alpha*=albedoTexture.a; #endif #ifdef GAMMAALBEDO surfaceAlbedo*=toLinearSpaceVec3(albedoTexture.rgb); #else surfaceAlbedo*=albedoTexture.rgb; #endif surfaceAlbedo*=albedoInfos.y; #endif #ifndef DECAL_AFTER_DETAIL #include #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) surfaceAlbedo*=fragmentInputs.vColor.rgb; #endif #ifdef DETAIL var detailAlbedo: f32=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; #endif #ifdef DECAL_AFTER_DETAIL #include #endif #define CUSTOM_FRAGMENT_UPDATE_ALBEDO #ifdef OPACITY #ifdef OPACITYRGB alpha=getLuminance(opacityMap.rgb); #else alpha*=opacityMap.a; #endif alpha*=vOpacityInfos.y; #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=fragmentInputs.vColor.a; #endif #if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) #ifdef ALPHATEST #if DEBUGMODE != 88 if (alpha0 #ifdef METALLICWORKFLOW metallicRoughness: vec2f, #ifdef REFLECTIVITY surfaceMetallicColorMap: vec4f, #endif #ifndef FROSTBITE_REFLECTANCE metallicF0: vec3f, #endif #else #ifdef REFLECTIVITY surfaceReflectivityColorMap: vec4f, #endif #endif #endif }; #define pbr_inline fn reflectivityBlock( vReflectivityColor: vec4f #ifdef METALLICWORKFLOW ,surfaceAlbedo: vec3f ,metallicReflectanceFactors: vec4f #endif #ifdef REFLECTIVITY ,reflectivityInfos: vec3f ,surfaceMetallicOrReflectivityColorMap: vec4f #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) ,ambientOcclusionColorIn: vec3f #endif #ifdef MICROSURFACEMAP ,microSurfaceTexel: vec4f #endif #ifdef DETAIL ,detailColor: vec4f ,vDetailInfos: vec4f #endif )->reflectivityOutParams {var outParams: reflectivityOutParams;var microSurface: f32=vReflectivityColor.a;var surfaceReflectivityColor: vec3f=vReflectivityColor.rgb; #ifdef METALLICWORKFLOW var metallicRoughness: vec2f=surfaceReflectivityColor.rg; #ifdef REFLECTIVITY #if DEBUGMODE>0 outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; #endif #ifdef AOSTOREINMETALMAPRED var aoStoreInMetalMap: vec3f= vec3f(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); #endif #ifdef METALLNESSSTOREINMETALMAPBLUE metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; #else metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; #endif #ifdef ROUGHNESSSTOREINMETALMAPALPHA metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; #else #ifdef ROUGHNESSSTOREINMETALMAPGREEN metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; #endif #endif #endif #ifdef DETAIL var detailRoughness: f32=mix(0.5,detailColor.b,vDetailInfos.w);var loLerp: f32=mix(0.,metallicRoughness.g,detailRoughness*2.);var hiLerp: f32=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); #endif #ifdef MICROSURFACEMAP metallicRoughness.g*=microSurfaceTexel.r; #endif #if DEBUGMODE>0 outParams.metallicRoughness=metallicRoughness; #endif #define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS microSurface=1.0-metallicRoughness.g;var baseColor: vec3f=surfaceAlbedo; #ifdef FROSTBITE_REFLECTANCE outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); #else var metallicF0: vec3f=metallicReflectanceFactors.rgb; #if DEBUGMODE>0 outParams.metallicF0=metallicF0; #endif outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0), vec3f(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); #endif #else #ifdef REFLECTIVITY surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; #if DEBUGMODE>0 outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; #endif #ifdef MICROSURFACEFROMREFLECTIVITYMAP microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; #else #ifdef MICROSURFACEAUTOMATIC microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); #endif #ifdef MICROSURFACEMAP microSurface*=microSurfaceTexel.r; #endif #define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE #endif #endif #endif microSurface=saturate(microSurface);var roughness: f32=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;} `;de.IncludesShadersStoreWGSL[gCt]=_Ct;const vCt="pbrBlockAmbientOcclusion",yCt=`struct ambientOcclusionOutParams {ambientOcclusionColor: vec3f, #if DEBUGMODE>0 && defined(AMBIENT) ambientOcclusionColorMap: vec3f #endif }; #define pbr_inline fn ambientOcclusionBlock( #ifdef AMBIENT ambientOcclusionColorMap_: vec3f, vAmbientInfos: vec4f #endif )->ambientOcclusionOutParams { var outParams: ambientOcclusionOutParams;var ambientOcclusionColor: vec3f= vec3f(1.,1.,1.); #ifdef AMBIENT var ambientOcclusionColorMap: vec3f=ambientOcclusionColorMap_*vAmbientInfos.y; #ifdef AMBIENTINGRAYSCALE ambientOcclusionColorMap= vec3f(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); #endif ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); #if DEBUGMODE>0 outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; #endif #endif outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;} `;de.IncludesShadersStoreWGSL[vCt]=yCt;const xCt="pbrBlockAlphaFresnel",ACt=`#ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) struct alphaFresnelOutParams {alpha: f32};fn faceforward(N: vec3,I: vec3,Nref: vec3)->vec3 {return select(N,-N,dot(Nref,I)>0.0);} #define pbr_inline fn alphaFresnelBlock( normalW: vec3f, viewDirectionW: vec3f, alpha: f32, microSurface: f32 )->alphaFresnelOutParams {var outParams: alphaFresnelOutParams;var opacityPerceptual: f32=alpha; #ifdef LINEARALPHAFRESNEL var opacity0: f32=opacityPerceptual; #else var opacity0: f32=opacityPerceptual*opacityPerceptual; #endif var opacity90: f32=fresnelGrazingReflectance(opacity0);var normalForward: vec3f=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)), vec3f(opacity0), vec3f(opacity90),sqrt(microSurface)).x; #ifdef ALPHATEST if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) anisotropyMapData: vec3f #endif }; #define pbr_inline fn anisotropicBlock( vAnisotropy: vec3f, roughness: f32, #ifdef ANISOTROPIC_TEXTURE anisotropyMapData: vec3f, #endif TBN: mat3x3f, normalW: vec3f, viewDirectionW: vec3f )->anisotropicOutParams { var outParams: anisotropicOutParams;var anisotropy: f32=vAnisotropy.b;var anisotropyDirection: vec3f= vec3f(vAnisotropy.xy,0.); #ifdef ANISOTROPIC_TEXTURE var amd=anisotropyMapData.rg;anisotropy*=anisotropyMapData.b; #if DEBUGMODE>0 outParams.anisotropyMapData=anisotropyMapData; #endif amd=amd*2.0-1.0; #ifdef ANISOTROPIC_LEGACY anisotropyDirection=vec3f(anisotropyDirection.xy*amd,anisotropyDirection.z); #else anisotropyDirection=vec3f(mat2x2f(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(amd),anisotropyDirection.z); #endif #endif var anisoTBN: mat3x3f= mat3x3f(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));var anisotropicTangent: vec3f=normalize(anisoTBN*anisotropyDirection);var anisotropicBitangent: vec3f=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;} #endif `;de.IncludesShadersStoreWGSL[bCt]=CCt;const SCt="pbrBlockReflection",ECt=`#ifdef REFLECTION struct reflectionOutParams {environmentRadiance: vec4f ,environmentIrradiance: vec3f #ifdef REFLECTIONMAP_3D ,reflectionCoords: vec3f #else ,reflectionCoords: vec2f #endif #ifdef SS_TRANSLUCENCY #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,irradianceVector: vec3f #endif #endif #endif }; #define pbr_inline #ifdef REFLECTIONMAP_3D fn createReflectionCoords( vPositionW: vec3f, normalW: vec3f, #ifdef ANISOTROPIC anisotropicOut: anisotropicOutParams, #endif )->vec3f {var reflectionCoords: vec3f; #else fn createReflectionCoords( vPositionW: vec3f, normalW: vec3f, #ifdef ANISOTROPIC anisotropicOut: anisotropicOutParams, #endif )->vec2f { var reflectionCoords: vec2f; #endif #ifdef ANISOTROPIC var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),anisotropicOut.anisotropicNormal); #else var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),normalW); #endif #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D reflectionCoords=reflectionVector; #else reflectionCoords=reflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION reflectionCoords/=reflectionVector.z; #endif reflectionCoords.y=1.0-reflectionCoords.y; #endif return reflectionCoords;} #define pbr_inline fn sampleReflectionTexture( alphaG: f32 ,vReflectionMicrosurfaceInfos: vec3f ,vReflectionInfos: vec2f ,vReflectionColor: vec3f #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,NdotVUnclamped: f32 #endif #ifdef LINEARSPECULARREFLECTION ,roughness: f32 #endif #ifdef REFLECTIONMAP_3D ,reflectionSampler: texture_cube ,reflectionSamplerSampler: sampler ,reflectionCoords: vec3f #else ,reflectionSampler: texture_2d ,reflectionSamplerSampler: sampler ,reflectionCoords: vec2f #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,reflectionLowSampler: texture_cube ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_cube ,reflectionHighSamplerSampler: sampler #else ,reflectionLowSampler: texture_2d ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_2d ,reflectionHighSamplerSampler: sampler #endif #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo: vec2f #endif )->vec4f {var environmentRadiance: vec4f; #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) var reflectionLOD: f32=getLodFromAlphaGNdotV(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); #elif defined(LINEARSPECULARREFLECTION) var reflectionLOD: f32=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); #else var reflectionLOD: f32=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); #endif #ifdef LODBASEDMICROSFURACE reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; #ifdef LODINREFLECTIONALPHA var automaticReflectionLOD: f32=UNPACK_LOD(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords).a);var requestedReflectionLOD: f32=max(automaticReflectionLOD,reflectionLOD); #else var requestedReflectionLOD: f32=reflectionLOD; #endif #ifdef REALTIME_FILTERING environmentRadiance= vec4f(radiance(alphaG,reflectionSampler,reflectionSamplerSampler,reflectionCoords,vReflectionFilteringInfo),1.0); #else environmentRadiance=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD); #endif #else var lodReflectionNormalized: f32=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var environmentMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( textureSample(reflectionHighSampler,reflectionHighSamplerSampler,reflectionCoords), environmentMid, lodReflectionNormalizedDoubled );} else {environmentRadiance=mix( environmentMid, textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords), lodReflectionNormalizedDoubled-1.0 );} #endif var envRadiance=environmentRadiance.rgb; #ifdef RGBDREFLECTION envRadiance=fromRGBD(environmentRadiance); #endif #ifdef GAMMAREFLECTION envRadiance=toLinearSpaceVec3(environmentRadiance.rgb); #endif envRadiance*=vReflectionInfos.x;envRadiance*=vReflectionColor.rgb;return vec4f(envRadiance,environmentRadiance.a);} #define pbr_inline fn reflectionBlock( vPositionW: vec3f ,normalW: vec3f ,alphaG: f32 ,vReflectionMicrosurfaceInfos: vec3f ,vReflectionInfos: vec2f ,vReflectionColor: vec3f #ifdef ANISOTROPIC ,anisotropicOut: anisotropicOutParams #endif #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,NdotVUnclamped: f32 #endif #ifdef LINEARSPECULARREFLECTION ,roughness: f32 #endif #ifdef REFLECTIONMAP_3D ,reflectionSampler: texture_cube ,reflectionSamplerSampler: sampler #else ,reflectionSampler: texture_2d ,reflectionSamplerSampler: sampler #endif #if defined(NORMAL) && defined(USESPHERICALINVERTEX) ,vEnvironmentIrradiance: vec3f #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,reflectionMatrix: mat4x4f #endif #endif #ifdef USEIRRADIANCEMAP #ifdef REFLECTIONMAP_3D ,irradianceSampler: texture_cube ,irradianceSamplerSampler: sampler #else ,irradianceSampler: texture_2d ,irradianceSamplerSampler: sampler #endif #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,reflectionLowSampler: texture_cube ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_cube ,reflectionHighSamplerSampler: sampler #else ,reflectionLowSampler: texture_2d ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_2d ,reflectionHighSamplerSampler: sampler #endif #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo: vec2f #endif )->reflectionOutParams {var outParams: reflectionOutParams;var environmentRadiance: vec4f= vec4f(0.,0.,0.,0.); #ifdef REFLECTIONMAP_3D var reflectionCoords: vec3f= vec3f(0.); #else var reflectionCoords: vec2f= vec2f(0.); #endif reflectionCoords=createReflectionCoords( vPositionW, normalW, #ifdef ANISOTROPIC anisotropicOut, #endif );environmentRadiance=sampleReflectionTexture( alphaG ,vReflectionMicrosurfaceInfos ,vReflectionInfos ,vReflectionColor #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,NdotVUnclamped #endif #ifdef LINEARSPECULARREFLECTION ,roughness #endif #ifdef REFLECTIONMAP_3D ,reflectionSampler ,reflectionSamplerSampler ,reflectionCoords #else ,reflectionSampler ,reflectionSamplerSampler ,reflectionCoords #endif #ifndef LODBASEDMICROSFURACE ,reflectionLowSampler ,reflectionLowSamplerSampler ,reflectionHighSampler ,reflectionHighSamplerSampler #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif );var environmentIrradiance: vec3f= vec3f(0.,0.,0.); #ifdef USESPHERICALFROMREFLECTIONMAP #if defined(NORMAL) && defined(USESPHERICALINVERTEX) environmentIrradiance=vEnvironmentIrradiance; #else #ifdef ANISOTROPIC var irradianceVector: vec3f= (reflectionMatrix* vec4f(anisotropicOut.anisotropicNormal,0)).xyz; #else var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz; #endif #ifdef REFLECTIONMAP_OPPOSITEZ irradianceVector.z*=-1.0; #endif #ifdef INVERTCUBICMAP irradianceVector.y*=-1.0; #endif #if defined(REALTIME_FILTERING) environmentIrradiance=irradiance(reflectionSampler,reflectionSamplerSampler,irradianceVector,vReflectionFilteringInfo); #else environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); #endif #ifdef SS_TRANSLUCENCY outParams.irradianceVector=irradianceVector; #endif #endif #elif defined(USEIRRADIANCEMAP) var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; #ifdef RGBDREFLECTION environmentIrradiance=fromRGBD(environmentIrradiance4); #endif #ifdef GAMMAREFLECTION environmentIrradiance=toLinearSpaceVec3(environmentIrradiance.rgb); #endif #endif environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;} #endif `;de.IncludesShadersStoreWGSL[SCt]=ECt;const TCt="pbrBlockSheen",MCt=`#ifdef SHEEN struct sheenOutParams {sheenIntensity: f32 ,sheenColor: vec3f ,sheenRoughness: f32 #ifdef SHEEN_LINKWITHALBEDO ,surfaceAlbedo: vec3f #endif #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) ,sheenAlbedoScaling: f32 #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) ,finalSheenRadianceScaled: vec3f #endif #if DEBUGMODE>0 #ifdef SHEEN_TEXTURE ,sheenMapData: vec4f #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) ,sheenEnvironmentReflectance: vec3f #endif #endif }; #define pbr_inline fn sheenBlock( vSheenColor: vec4f #ifdef SHEEN_ROUGHNESS ,vSheenRoughness: f32 #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) ,sheenMapRoughnessData: vec4f #endif #endif ,roughness: f32 #ifdef SHEEN_TEXTURE ,sheenMapData: vec4f ,sheenMapLevel: f32 #endif ,reflectance: f32 #ifdef SHEEN_LINKWITHALBEDO ,baseColor: vec3f ,surfaceAlbedo: vec3f #endif #ifdef ENVIRONMENTBRDF ,NdotV: f32 ,environmentBrdf: vec3f #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) ,AARoughnessFactors: vec2f ,vReflectionMicrosurfaceInfos: vec3f ,vReflectionInfos: vec2f ,vReflectionColor: vec3f ,vLightingIntensity: vec4f #ifdef REFLECTIONMAP_3D ,reflectionSampler: texture_cube ,reflectionSamplerSampler: sampler ,reflectionCoords: vec3f #else ,reflectionSampler: texture_2d ,reflectionSamplerSampler: sampler ,reflectionCoords: vec2f #endif ,NdotVUnclamped: f32 #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,reflectionLowSampler: texture_cube ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_cube ,reflectionHighSamplerSampler: sampler #else ,reflectionLowSampler: texture_2d ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_2d ,reflectionHighSamplerSampler: sampler #endif #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo: vec2f #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) ,seo: f32 #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) ,eho: f32 #endif #endif )->sheenOutParams {var outParams: sheenOutParams;var sheenIntensity: f32=vSheenColor.a; #ifdef SHEEN_TEXTURE #if DEBUGMODE>0 outParams.sheenMapData=sheenMapData; #endif #endif #ifdef SHEEN_LINKWITHALBEDO var sheenFactor: f32=pow5(1.0-sheenIntensity);var sheenColor: vec3f=baseColor.rgb*(1.0-sheenFactor);var sheenRoughness: f32=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; #ifdef SHEEN_TEXTURE sheenIntensity*=sheenMapData.a; #endif #else var sheenColor: vec3f=vSheenColor.rgb; #ifdef SHEEN_TEXTURE #ifdef SHEEN_GAMMATEXTURE sheenColor*=toLinearSpaceVec3(sheenMapData.rgb); #else sheenColor*=sheenMapData.rgb; #endif sheenColor*=sheenMapLevel; #endif #ifdef SHEEN_ROUGHNESS var sheenRoughness: f32=vSheenRoughness; #ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE #if defined(SHEEN_TEXTURE) sheenRoughness*=sheenMapData.a; #endif #elif defined(SHEEN_TEXTURE_ROUGHNESS) sheenRoughness*=sheenMapRoughnessData.a; #endif #else var sheenRoughness: f32=roughness; #ifdef SHEEN_TEXTURE sheenIntensity*=sheenMapData.a; #endif #endif #if !defined(SHEEN_ALBEDOSCALING) sheenIntensity*=(1.-reflectance); #endif sheenColor*=sheenIntensity; #endif #ifdef ENVIRONMENTBRDF /*#ifdef SHEEN_SOFTER var environmentSheenBrdf: vec3f= vec3f(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); #else*/ #ifdef SHEEN_ROUGHNESS var environmentSheenBrdf: vec3f=getBRDFLookup(NdotV,sheenRoughness); #else var environmentSheenBrdf: vec3f=environmentBrdf; #endif /*#endif*/ #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) var sheenAlphaG: f32=convertRoughnessToAverageSlope(sheenRoughness); #ifdef SPECULARAA sheenAlphaG+=AARoughnessFactors.y; #endif var environmentSheenRadiance: vec4f= vec4f(0.,0.,0.,0.);environmentSheenRadiance=sampleReflectionTexture( sheenAlphaG ,vReflectionMicrosurfaceInfos ,vReflectionInfos ,vReflectionColor #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,NdotVUnclamped #endif #ifdef LINEARSPECULARREFLECTION ,sheenRoughness #endif ,reflectionSampler ,reflectionSamplerSampler ,reflectionCoords #ifndef LODBASEDMICROSFURACE ,reflectionLowSampler ,reflectionLowSamplerSampler ,reflectionHighSampler ,reflectionHighSamplerSampler #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif );var sheenEnvironmentReflectance: vec3f=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) sheenEnvironmentReflectance*=seo; #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) sheenEnvironmentReflectance*=eho; #endif #if DEBUGMODE>0 outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; #endif outParams.finalSheenRadianceScaled= environmentSheenRadiance.rgb * sheenEnvironmentReflectance * vLightingIntensity.z; #endif #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; #endif outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;} #endif `;de.IncludesShadersStoreWGSL[TCt]=MCt;const RCt="pbrBlockClearcoat",ICt=`struct clearcoatOutParams {specularEnvironmentR0: vec3f, conservationFactor: f32, clearCoatNormalW: vec3f, clearCoatAARoughnessFactors: vec2f, clearCoatIntensity: f32, clearCoatRoughness: f32, #ifdef REFLECTION finalClearCoatRadianceScaled: vec3f, #endif #ifdef CLEARCOAT_TINT absorption: vec3f, clearCoatNdotVRefract: f32, clearCoatColor: vec3f, clearCoatThickness: f32, #endif #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) energyConservationFactorClearCoat: vec3f, #endif #if DEBUGMODE>0 #ifdef CLEARCOAT_BUMP TBNClearCoat: mat3x3f, #endif #ifdef CLEARCOAT_TEXTURE clearCoatMapData: vec2f, #endif #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) clearCoatTintMapData: vec4f, #endif #ifdef REFLECTION environmentClearCoatRadiance: vec4f, clearCoatEnvironmentReflectance: vec3f, #endif clearCoatNdotV: f32 #endif }; #ifdef CLEARCOAT #define pbr_inline fn clearcoatBlock( vPositionW: vec3f ,geometricNormalW: vec3f ,viewDirectionW: vec3f ,vClearCoatParams: vec2f #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) ,clearCoatMapRoughnessData: vec4f #endif ,specularEnvironmentR0: vec3f #ifdef CLEARCOAT_TEXTURE ,clearCoatMapData: vec2f #endif #ifdef CLEARCOAT_TINT ,vClearCoatTintParams: vec4f ,clearCoatColorAtDistance: f32 ,vClearCoatRefractionParams: vec4f #ifdef CLEARCOAT_TINT_TEXTURE ,clearCoatTintMapData: vec4f #endif #endif #ifdef CLEARCOAT_BUMP ,vClearCoatBumpInfos: vec2f ,clearCoatBumpMapData: vec4f ,vClearCoatBumpUV: vec2f #if defined(TANGENT) && defined(NORMAL) ,vTBN: mat3x3f #else ,vClearCoatTangentSpaceParams: vec2f #endif #ifdef OBJECTSPACE_NORMALMAP ,normalMatrix: mat4x4f #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) ,faceNormal: vec3f #endif #ifdef REFLECTION ,vReflectionMicrosurfaceInfos: vec3f ,vReflectionInfos: vec2f ,vReflectionColor: vec3f ,vLightingIntensity: vec4f #ifdef REFLECTIONMAP_3D ,reflectionSampler: texture_cube ,reflectionSamplerSampler: sampler #else ,reflectionSampler: texture_2d ,reflectionSamplerSampler: sampler #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,reflectionLowSampler: texture_cube ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_cube ,reflectionHighSamplerSampler: sampler #else ,reflectionLowSampler: texture_2d ,reflectionLowSamplerSampler: sampler ,reflectionHighSampler: texture_2d ,reflectionHighSamplerSampler: sampler #endif #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo: vec2f #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION ,ambientMonochrome: f32 #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) ,frontFacingMultiplier: f32 #endif )->clearcoatOutParams {var outParams: clearcoatOutParams;var clearCoatIntensity: f32=vClearCoatParams.x;var clearCoatRoughness: f32=vClearCoatParams.y; #ifdef CLEARCOAT_TEXTURE clearCoatIntensity*=clearCoatMapData.x; #ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE clearCoatRoughness*=clearCoatMapData.y; #endif #if DEBUGMODE>0 outParams.clearCoatMapData=clearCoatMapData; #endif #endif #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) clearCoatRoughness*=clearCoatMapRoughnessData.y; #endif outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; #ifdef CLEARCOAT_TINT var clearCoatColor: vec3f=vClearCoatTintParams.rgb;var clearCoatThickness: f32=vClearCoatTintParams.a; #ifdef CLEARCOAT_TINT_TEXTURE #ifdef CLEARCOAT_TINT_GAMMATEXTURE clearCoatColor*=toLinearSpaceVec3(clearCoatTintMapData.rgb); #else clearCoatColor*=clearCoatTintMapData.rgb; #endif clearCoatThickness*=clearCoatTintMapData.a; #if DEBUGMODE>0 outParams.clearCoatTintMapData=clearCoatTintMapData; #endif #endif outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; #endif #ifdef CLEARCOAT_REMAP_F0 var specularEnvironmentR0Updated: vec3f=getR0RemappedForClearCoat(specularEnvironmentR0); #else var specularEnvironmentR0Updated: vec3f=specularEnvironmentR0; #endif outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);var clearCoatNormalW: vec3f=geometricNormalW; #ifdef CLEARCOAT_BUMP #ifdef NORMALXYSCALE var clearCoatNormalScale: f32=1.0; #else var clearCoatNormalScale: f32=vClearCoatBumpInfos.y; #endif #if defined(TANGENT) && defined(NORMAL) var TBNClearCoat: mat3x3f=vTBN; #else var TBNClearCoatUV: vec2f=vClearCoatBumpUV*frontFacingMultiplier;var TBNClearCoat: mat3x3f=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); #endif #if DEBUGMODE>0 outParams.TBNClearCoat=TBNClearCoat; #endif #ifdef OBJECTSPACE_NORMALMAP clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize( mat3x3f(normalMatrix[0].xyz,normalMatrix[1].xyz,normalMatrix[2].xyz)*clearCoatNormalW); #else clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); #endif #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; #endif outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);var clearCoatNdotVUnclamped: f32=dot(clearCoatNormalW,viewDirectionW);var clearCoatNdotV: f32=absEps(clearCoatNdotVUnclamped); #if DEBUGMODE>0 outParams.clearCoatNdotV=clearCoatNdotV; #endif #ifdef CLEARCOAT_TINT var clearCoatVRefract: vec3f=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); #endif #if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) var environmentClearCoatBrdf: vec3f=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); #endif #if defined(REFLECTION) var clearCoatAlphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness); #ifdef SPECULARAA clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; #endif var environmentClearCoatRadiance: vec4f= vec4f(0.,0.,0.,0.);var clearCoatReflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),clearCoatNormalW); #ifdef REFLECTIONMAP_OPPOSITEZ clearCoatReflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D var clearCoatReflectionCoords: vec3f=clearCoatReflectionVector; #else var clearCoatReflectionCoords: vec2f=clearCoatReflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION clearCoatReflectionCoords/=clearCoatReflectionVector.z; #endif clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; #endif environmentClearCoatRadiance=sampleReflectionTexture( clearCoatAlphaG ,vReflectionMicrosurfaceInfos ,vReflectionInfos ,vReflectionColor #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,clearCoatNdotVUnclamped #endif #ifdef LINEARSPECULARREFLECTION ,clearCoatRoughness #endif ,reflectionSampler ,reflectionSamplerSampler ,clearCoatReflectionCoords #ifndef LODBASEDMICROSFURACE ,reflectionLowSampler ,reflectionLowSamplerSampler ,reflectionHighSampler ,reflectionHighSamplerSampler #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif ); #if DEBUGMODE>0 outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromBRDFLookup(vec3f(uniforms.vClearCoatRefractionParams.x),environmentClearCoatBrdf); #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D var clearCoatEho: f32=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; #endif #endif #endif #else var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV, vec3f(1.), vec3f(1.),sqrt(1.-clearCoatRoughness)); #endif clearCoatEnvironmentReflectance*=clearCoatIntensity; #if DEBUGMODE>0 outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; #endif outParams.finalClearCoatRadianceScaled= environmentClearCoatRadiance.rgb * clearCoatEnvironmentReflectance * vLightingIntensity.z; #endif #if defined(CLEARCOAT_TINT) outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); #endif var fresnelIBLClearCoat: f32=fresnelSchlickGGX(clearCoatNdotV,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); #endif return outParams;} #endif `;de.IncludesShadersStoreWGSL[RCt]=ICt;const PCt="pbrBlockIridescence",wCt=`struct iridescenceOutParams {iridescenceIntensity: f32, iridescenceIOR: f32, iridescenceThickness: f32, specularEnvironmentR0: vec3f}; #ifdef IRIDESCENCE fn iridescenceBlock( vIridescenceParams: vec4f ,viewAngle: f32 ,specularEnvironmentR0: vec3f #ifdef IRIDESCENCE_TEXTURE ,iridescenceMapData: vec2f #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE ,iridescenceThicknessMapData: vec2f #endif #ifdef CLEARCOAT ,NdotVUnclamped: f32 #ifdef CLEARCOAT_TEXTURE ,clearCoatMapData: vec2f #endif #endif )->iridescenceOutParams {var outParams: iridescenceOutParams;var iridescenceIntensity: f32=vIridescenceParams.x;var iridescenceIOR: f32=vIridescenceParams.y;var iridescenceThicknessMin: f32=vIridescenceParams.z;var iridescenceThicknessMax: f32=vIridescenceParams.w;var iridescenceThicknessWeight: f32=1.; #ifdef IRIDESCENCE_TEXTURE iridescenceIntensity*=iridescenceMapData.x; #endif #if defined(IRIDESCENCE_THICKNESS_TEXTURE) iridescenceThicknessWeight=iridescenceThicknessMapData.g; #endif var iridescenceThickness: f32=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);var topIor: f32=1.; #ifdef CLEARCOAT var clearCoatIntensity: f32=vClearCoatParams.x; #ifdef CLEARCOAT_TEXTURE clearCoatIntensity*=clearCoatMapData.x; #endif topIor=mix(1.0,uniforms.vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+((1.0/topIor)*(1.0/topIor))*((NdotVUnclamped*NdotVUnclamped)-1.0)); #endif var iridescenceFresnel: vec3f=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;} #endif `;de.IncludesShadersStoreWGSL[PCt]=wCt;const DCt="pbrBlockSubSurface",LCt=`struct subSurfaceOutParams {specularEnvironmentReflectance: vec3f, #ifdef SS_REFRACTION finalRefraction: vec3f, surfaceAlbedo: vec3f, #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha: f32, #endif #ifdef REFLECTION refractionFactorForIrradiance: f32, #endif #endif #ifdef SS_TRANSLUCENCY transmittance: vec3f, translucencyIntensity: f32, #ifdef REFLECTION refractionIrradiance: vec3f, #endif #endif #if DEBUGMODE>0 #ifdef SS_THICKNESSANDMASK_TEXTURE thicknessMap: vec4f, #endif #ifdef SS_REFRACTION environmentRefraction: vec4f, refractionTransmittance: vec3f #endif #endif }; #ifdef SUBSURFACE #ifdef SS_REFRACTION #define pbr_inline fn sampleEnvironmentRefraction( ior: f32 ,thickness: f32 ,refractionLOD: f32 ,normalW: vec3f ,vPositionW: vec3f ,viewDirectionW: vec3f ,view: mat4x4f ,vRefractionInfos: vec4f ,refractionMatrix: mat4x4f ,vRefractionMicrosurfaceInfos: vec4f ,alphaG: f32 #ifdef SS_REFRACTIONMAP_3D ,refractionSampler: texture_cube ,refractionSamplerSampler: sampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler: texture_cube ,refractionLowSamplerSampler: sampler ,refractionHighSampler: texture_cube ,refractionHighSamplerSampler: sampler #endif #else ,refractionSampler: texture_2d ,refractionSamplerSampler: sampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler: texture_2d ,refractionLowSamplerSampler: sampler ,refractionHighSampler: texture_2d ,refractionHighSamplerSampler: sampler #endif #endif #ifdef ANISOTROPIC ,anisotropicOut: anisotropicOutParams #endif #ifdef REALTIME_FILTERING ,vRefractionFilteringInfo: vec2f #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,refractionPosition: vec3f ,refractionSize: vec3f #endif )->vec4f {var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.); #ifdef ANISOTROPIC var refractionVector: vec3f=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); #else var refractionVector: vec3f=refract(-viewDirectionW,normalW,ior); #endif #ifdef SS_REFRACTIONMAP_OPPOSITEZ refractionVector.z*=-1.0; #endif #ifdef SS_REFRACTIONMAP_3D #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); #endif refractionVector.y=refractionVector.y*vRefractionInfos.w;var refractionCoords: vec3f=refractionVector;refractionCoords= (refractionMatrix* vec4f(refractionCoords,0)).xyz; #else #ifdef SS_USE_THICKNESS_AS_DEPTH var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*thickness,1.0))).xyz; #else var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*vRefractionInfos.z,1.0))).xyz; #endif var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; #endif #ifdef LODBASEDMICROSFURACE var lod=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; #ifdef SS_LODINREFRACTIONALPHA var automaticRefractionLOD: f32=UNPACK_LOD(textureSample(refractionSampler,refractionSamplerSampler,refractionCoords).a);var requestedRefractionLOD: f32=max(automaticRefractionLOD,lod); #else var requestedRefractionLOD: f32=lod; #endif #if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) environmentRefraction= vec4f(radiance(alphaG,refractionSampler,refractionSamplerSampler,refractionCoords,vRefractionFilteringInfo),1.0); #else environmentRefraction=textureSampleLevel(refractionSampler,refractionSamplerSampler,refractionCoords,requestedRefractionLOD); #endif #else var lodRefractionNormalized: f32=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));var lodRefractionNormalizedDoubled: f32=lodRefractionNormalized*2.0;var environmentRefractionMid: vec4f=textureSample(refractionSampler,refractionSamplerSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( textureSample(refractionHighSampler,refractionHighSamplerSampler,refractionCoords), environmentRefractionMid, lodRefractionNormalizedDoubled );} else {environmentRefraction=mix( environmentRefractionMid, textureSample(refractionLowSampler,refractionLowSamplerSampler,refractionCoords), lodRefractionNormalizedDoubled-1.0 );} #endif var refraction=environmentRefraction.rgb; #ifdef SS_RGBDREFRACTION refraction=fromRGBD(environmentRefraction); #endif #ifdef SS_GAMMAREFRACTION refraction=toLinearSpaceVec3(environmentRefraction.rgb); #endif return vec4f(refraction,environmentRefraction.a);} #endif #define pbr_inline fn subSurfaceBlock( vSubSurfaceIntensity: vec3f ,vThicknessParam: vec2f ,vTintColor: vec4f ,normalW: vec3f ,specularEnvironmentReflectance: vec3f #ifdef SS_THICKNESSANDMASK_TEXTURE ,thicknessMap: vec4f #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE ,refractionIntensityMap: vec4f #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE ,translucencyIntensityMap: vec4f #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY ,reflectionMatrix: mat4x4f #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,irradianceVector_: vec3f #endif #if defined(REALTIME_FILTERING) ,reflectionSampler: texture_cube ,reflectionSamplerSampler: sampler ,vReflectionFilteringInfo: vec2f #endif #endif #ifdef USEIRRADIANCEMAP #ifdef REFLECTIONMAP_3D ,irradianceSampler: texture_cube ,irradianceSamplerSampler: sampler #else ,irradianceSampler: texture_2d ,irradianceSamplerSampler: sampler #endif #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) ,surfaceAlbedo: vec3f #endif #ifdef SS_REFRACTION ,vPositionW: vec3f ,viewDirectionW: vec3f ,view: mat4x4f ,vRefractionInfos: vec4f ,refractionMatrix: mat4x4f ,vRefractionMicrosurfaceInfos: vec4f ,vLightingIntensity: vec4f #ifdef SS_LINKREFRACTIONTOTRANSPARENCY ,alpha: f32 #endif #ifdef SS_LODINREFRACTIONALPHA ,NdotVUnclamped: f32 #endif #ifdef SS_LINEARSPECULARREFRACTION ,roughness: f32 #endif ,alphaG: f32 #ifdef SS_REFRACTIONMAP_3D ,refractionSampler: texture_cube ,refractionSamplerSampler: sampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler: texture_cube ,refractionLowSamplerSampler: sampler ,refractionHighSampler: texture_cube ,refractionHighSamplerSampler: sampler #endif #else ,refractionSampler: texture_2d ,refractionSamplerSampler: sampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler: texture_2d ,refractionLowSamplerSampler: sampler ,refractionHighSampler: texture_2d ,refractionHighSamplerSampler: sampler #endif #endif #ifdef ANISOTROPIC ,anisotropicOut: anisotropicOutParams #endif #ifdef REALTIME_FILTERING ,vRefractionFilteringInfo: vec2f #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,refractionPosition: vec3f ,refractionSize: vec3f #endif #ifdef SS_DISPERSION ,dispersion: f32 #endif #endif #ifdef SS_TRANSLUCENCY ,vDiffusionDistance: vec3f ,vTranslucencyColor: vec4f #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE ,translucencyColorMap: vec4f #endif #endif )->subSurfaceOutParams {var outParams: subSurfaceOutParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; #ifdef SS_REFRACTION var refractionIntensity: f32=vSubSurfaceIntensity.x; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; #endif #endif #ifdef SS_TRANSLUCENCY var translucencyIntensity: f32=vSubSurfaceIntensity.y; #endif #ifdef SS_THICKNESSANDMASK_TEXTURE #ifdef SS_USE_GLTF_TEXTURES var thickness: f32=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; #else var thickness: f32=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; #endif #if DEBUGMODE>0 outParams.thicknessMap=thicknessMap; #endif #if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS) #ifdef SS_USE_GLTF_TEXTURES refractionIntensity*=thicknessMap.r; #else refractionIntensity*=thicknessMap.g; #endif #endif #if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS) #ifdef SS_USE_GLTF_TEXTURES translucencyIntensity*=thicknessMap.a; #else translucencyIntensity*=thicknessMap.b; #endif #endif #else var thickness: f32=vThicknessParam.y; #endif #if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE) #ifdef SS_USE_GLTF_TEXTURES refractionIntensity*=refractionIntensityMap.r; #else refractionIntensity*=refractionIntensityMap.g; #endif #endif #if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE) #ifdef SS_USE_GLTF_TEXTURES translucencyIntensity*=translucencyIntensityMap.a; #else translucencyIntensity*=translucencyIntensityMap.b; #endif #endif #ifdef SS_TRANSLUCENCY thickness=maxEps(thickness);var translucencyColor: vec4f=vTranslucencyColor; #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE translucencyColor*=translucencyColorMap; #endif var transmittance: vec3f=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; #endif #ifdef SS_REFRACTION var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.); #ifdef SS_HAS_THICKNESS var ior: f32=vRefractionInfos.y; #else var ior: f32=vRefractionMicrosurfaceInfos.w; #endif #ifdef SS_LODINREFRACTIONALPHA var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaGNdotV(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); #elif defined(SS_LINEARSPECULARREFRACTION) var refractionRoughness: f32=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); #else var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); #endif var refraction_ior: f32=vRefractionInfos.y; #ifdef SS_DISPERSION var realIOR: f32=1.0/refraction_ior;var iorDispersionSpread: f32=0.04*dispersion*(realIOR-1.0);var iors: vec3f= vec3f(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (var i: i32=0; i<3; i++) {refraction_ior=iors[i]; #endif var envSample: vec4f=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG #ifdef SS_REFRACTIONMAP_3D ,refractionSampler ,refractionSamplerSampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler ,refractionLowSamplerSampler ,refractionHighSampler ,refractionHighSamplerSampler #endif #else ,refractionSampler ,refractionSamplerSampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler ,refractionLowSamplerSampler ,refractionHighSampler ,refractionHighSamplerSampler #endif #endif #ifdef ANISOTROPIC ,anisotropicOut #endif #ifdef REALTIME_FILTERING ,vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,refractionPosition ,refractionSize #endif ); #ifdef SS_DISPERSION environmentRefraction[i]=envSample[i];} #else environmentRefraction=envSample; #endif environmentRefraction=vec4f(environmentRefraction.rgb*vRefractionInfos.x,environmentRefraction.a); #endif #ifdef SS_REFRACTION var refractionTransmittance: vec3f= vec3f(refractionIntensity); #ifdef SS_THICKNESSANDMASK_TEXTURE var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,thickness); #elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) var maxChannel: f32=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);var volumeAlbedo: vec3f=saturateVec3(maxChannel*surfaceAlbedo);environmentRefraction=vec4f(environmentRefraction.rgb*volumeAlbedo,environmentRefraction.a); #else var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,vThicknessParam.y); #endif #ifdef SS_ALBEDOFORREFRACTIONTINT environmentRefraction=vec4f(environmentRefraction.rgb*surfaceAlbedo.rgb,environmentRefraction.a); #endif outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); #ifdef REFLECTION outParams.refractionFactorForIrradiance=(1.-refractionIntensity); #endif #ifdef UNUSED_MULTIPLEBOUNCES var bounceSpecularEnvironmentReflectance: vec3f=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); #endif refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; #if DEBUGMODE>0 outParams.refractionTransmittance=refractionTransmittance; #endif outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; #if DEBUGMODE>0 outParams.environmentRefraction=environmentRefraction; #endif #endif #if defined(REFLECTION) && defined(SS_TRANSLUCENCY) #if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz; #ifdef REFLECTIONMAP_OPPOSITEZ irradianceVector.z*=-1.0; #endif #ifdef INVERTCUBICMAP irradianceVector.y*=-1.0; #endif #else var irradianceVector: vec3f=irradianceVector_; #endif #if defined(USESPHERICALFROMREFLECTIONMAP) #if defined(REALTIME_FILTERING) var refractionIrradiance: vec3f=irradiance(reflectionSampler,reflectionSamplerSampler,-irradianceVector,vReflectionFilteringInfo); #else var refractionIrradiance: vec3f=computeEnvironmentIrradiance(-irradianceVector); #endif #elif defined(USEIRRADIANCEMAP) #ifdef REFLECTIONMAP_3D var irradianceCoords: vec3f=irradianceVector; #else var irradianceCoords: vec2f=irradianceVector.xy; #ifdef REFLECTIONMAP_PROJECTION irradianceCoords/=irradianceVector.z; #endif irradianceCoords.y=1.0-irradianceCoords.y; #endif var temp: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,-irradianceCoords);var refractionIrradiance=temp.rgb; #ifdef RGBDREFLECTION refractionIrradiance=fromRGBD(temp).rgb; #endif #ifdef GAMMAREFLECTION refractionIrradiance=toLinearSpaceVec3(refractionIrradiance); #endif #else var refractionIrradiance: vec3f= vec3f(0.); #endif refractionIrradiance*=transmittance; #ifdef SS_ALBEDOFORTRANSLUCENCYTINT refractionIrradiance*=surfaceAlbedo.rgb; #endif outParams.refractionIrradiance=refractionIrradiance; #endif return outParams;} #endif `;de.IncludesShadersStoreWGSL[DCt]=LCt;const OCt="pbrBlockNormalGeometric",NCt=`var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW); #ifdef NORMAL var normalW: vec3f=normalize(input.vNormalW); #else var normalW: vec3f=normalize(cross(dpdx(input.vPositionW),dpdy(input.vPositionW)))*scene.vEyePosition.w; #endif var geometricNormalW: vec3f=normalW; #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) geometricNormalW=select(-geometricNormalW,geometricNormalW,fragmentInputs.frontFacing); #endif `;de.IncludesShadersStoreWGSL[OCt]=NCt;const jWe="bumpFragment",XWe=`var uvOffset: vec2f= vec2f(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE var normalScale: f32=1.0; #elif defined(BUMP) var normalScale: f32=uniforms.vBumpInfos.y; #else var normalScale: f32=1.0; #endif #if defined(TANGENT) && defined(NORMAL) var TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); #elif defined(BUMP) var TBNUV: vec2f=select(-fragmentInputs.vBumpUV,fragmentInputs.vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams); #else var TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.)); #endif #elif defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) var TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); #else var TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.)); #endif #endif #ifdef PARALLAX var invTBN: mat3x3f=transposeMat3(TBN); #ifdef PARALLAXOCCLUSION uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,fragmentInputs.vBumpUV,uniforms.vBumpInfos.z); #else uvOffset=parallaxOffset(invTBN*viewDirectionW,uniforms.vBumpInfos.z); #endif #endif #ifdef DETAIL var detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB); #endif #ifdef BUMP #ifdef OBJECTSPACE_NORMALMAP #define CUSTOM_FRAGMENT_BUMP_FRAGMENT normalW=normalize(textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW); #elif !defined(DETAIL) normalW=perturbNormal(TBN,textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz,uniforms.vBumpInfos.y); #else var bumpNormal: vec3f=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz*2.0-1.0; #if DETAIL_NORMALBLENDMETHOD==0 detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); #elif DETAIL_NORMALBLENDMETHOD==1 detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; #endif normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y); #endif #elif defined(DETAIL) detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z); #endif `;de.IncludesShadersStoreWGSL[jWe]=XWe;const YWe={name:jWe,shader:XWe},FCt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentWGSL:YWe},Symbol.toStringTag,{value:"Module"})),BCt="pbrBlockNormalFinal",kCt=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing); #endif normalW*=sign(dot(normalW,faceNormal)); #endif #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) normalW=select(-normalW,normalW,fragmentInputs.frontFacing); #endif `;de.IncludesShadersStoreWGSL[BCt]=kCt;const UCt="depthPrePass",zCt=`#ifdef DEPTHPREPASS fragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs; #endif `;de.IncludesShadersStoreWGSL[UCt]=zCt;const VCt="pbrBlockLightmapInit",GCt=`#ifdef LIGHTMAP var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a); #endif #ifdef GAMMALIGHTMAP lightmapColor=vec4f(toLinearSpaceVec3(lightmapColor.rgb),lightmapColor.a); #endif lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a); #endif `;de.IncludesShadersStoreWGSL[VCt]=GCt;const WCt="pbrBlockGeometryInfo",KCt=`var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz); #ifdef SPECULARAA alphaG+=AARoughnessFactors.y; #endif #if defined(ENVIRONMENTBRDF) var environmentBrdf: vec3f=getBRDFLookup(NdotV,roughness); #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION #ifdef AMBIENTINGRAYSCALE var ambientMonochrome: f32=aoOut.ambientOcclusionColor.r; #else var ambientMonochrome: f32=getLuminance(aoOut.ambientOcclusionColor); #endif var seo: f32=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); #endif #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D var eho: f32=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); #endif #endif #endif #endif `;de.IncludesShadersStoreWGSL[WCt]=KCt;const HCt="pbrBlockReflectance0",jCt=`var reflectance: f32=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);var specularEnvironmentR0: vec3f=reflectivityOut.surfaceReflectivityColor.rgb; #ifdef METALLICWORKFLOW var specularEnvironmentR90: vec3f= vec3f(metallicReflectanceFactors.a); #else var specularEnvironmentR90: vec3f= vec3f(1.0,1.0,1.0); #endif #ifdef ALPHAFRESNEL var reflectance90: f32=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; #endif `;de.IncludesShadersStoreWGSL[HCt]=jCt;const XCt="pbrBlockReflectance",YCt=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) var specularEnvironmentReflectance: vec3f=getReflectanceFromBRDFWithEnvLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); #ifdef RADIANCEOCCLUSION specularEnvironmentReflectance*=seo; #endif #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D specularEnvironmentReflectance*=eho; #endif #endif #endif #else var specularEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); #endif #ifdef CLEARCOAT specularEnvironmentReflectance*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) specularEnvironmentReflectance*=clearcoatOut.absorption; #endif #endif `;de.IncludesShadersStoreWGSL[XCt]=YCt;const QCt="pbrBlockDirectLighting",$Ct=`var diffuseBase: vec3f=vec3f(0.,0.,0.); #ifdef SPECULARTERM var specularBase: vec3f=vec3f(0.,0.,0.); #endif #ifdef CLEARCOAT var clearCoatBase: vec3f=vec3f(0.,0.,0.); #endif #ifdef SHEEN var sheenBase: vec3f=vec3f(0.,0.,0.); #endif var preInfo: preLightingInfo;var info: lightingInfo;var shadow: f32=1.; var aggShadow: f32=0.;var numLights: f32=0.; #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) var absorption: vec3f=vec3f(0.); #endif `;de.IncludesShadersStoreWGSL[QCt]=$Ct;const ZCt="pbrBlockFinalLitComponents",qCt=`aggShadow=aggShadow/numLights; #if defined(ENVIRONMENTBRDF) #ifdef MS_BRDF_ENERGY_CONSERVATION var energyConservationFactor: vec3f=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); #endif #endif #ifndef METALLICWORKFLOW #ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION surfaceAlbedo=(1.-reflectance)*surfaceAlbedo.rgb; #endif #endif #if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) surfaceAlbedo=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; #endif #ifdef REFLECTION var finalIrradiance: vec3f=reflectionOut.environmentIrradiance; #if defined(CLEARCOAT) finalIrradiance*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) finalIrradiance*=clearcoatOut.absorption; #endif #endif #if defined(SS_REFRACTION) finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; #endif #if defined(SS_TRANSLUCENCY) finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; #endif finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=uniforms.vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; #endif #ifdef SPECULARTERM var finalSpecular: vec3f=specularBase;finalSpecular=max(finalSpecular,vec3f(0.0));var finalSpecularScaled: vec3f=finalSpecular*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalSpecularScaled*=energyConservationFactor; #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) finalSpecularScaled*=sheenOut.sheenAlbedoScaling; #endif #endif #ifdef REFLECTION var finalRadiance: vec3f=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;var finalRadianceScaled: vec3f=finalRadiance*uniforms.vLightingIntensity.z; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalRadianceScaled*=energyConservationFactor; #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) finalRadianceScaled*=sheenOut.sheenAlbedoScaling; #endif #endif #ifdef SHEEN var finalSheen: vec3f=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,vec3f(0.0));var finalSheenScaled: vec3f=finalSheen*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w; #if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; #endif #endif #endif #ifdef CLEARCOAT var finalClearCoat: vec3f=clearCoatBase;finalClearCoat=max(finalClearCoat,vec3f(0.0));var finalClearCoatScaled: vec3f=finalClearCoat*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; #endif #ifdef SS_REFRACTION subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; #ifdef CLEARCOAT_TINT subSurfaceOut.finalRefraction*=clearcoatOut.absorption; #endif #endif #endif #ifdef ALPHABLEND var luminanceOverAlpha: f32=0.0; #if defined(REFLECTION) && defined(RADIANCEOVERALPHA) luminanceOverAlpha+=getLuminance(finalRadianceScaled); #if defined(CLEARCOAT) luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); #endif #endif #if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) luminanceOverAlpha+=getLuminance(finalSpecularScaled); #endif #if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) luminanceOverAlpha+=getLuminance(finalClearCoatScaled); #endif #if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); #endif #endif `;de.IncludesShadersStoreWGSL[ZCt]=qCt;const JCt="pbrBlockFinalUnlitComponents",eSt=`var finalDiffuse: vec3f=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,vec3f(0.0));finalDiffuse*=uniforms.vLightingIntensity.x;var finalAmbient: vec3f=uniforms.vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;var finalEmissive: vec3f=uniforms.vEmissiveColor; #ifdef EMISSIVE var emissiveColorTex: vec3f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb; #ifdef GAMMAEMISSIVE finalEmissive*=toLinearSpaceVec3(emissiveColorTex.rgb); #else finalEmissive*=emissiveColorTex.rgb; #endif finalEmissive*= uniforms.vEmissiveInfos.y; #endif finalEmissive*=uniforms.vLightingIntensity.y; #ifdef AMBIENT var ambientOcclusionForDirectDiffuse: vec3f=mix( vec3f(1.),aoOut.ambientOcclusionColor,uniforms.vAmbientInfos.w); #else var ambientOcclusionForDirectDiffuse: vec3f=aoOut.ambientOcclusionColor; #endif finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; `;de.IncludesShadersStoreWGSL[JCt]=eSt;const tSt="pbrBlockFinalColorComposition",iSt=`var finalColor: vec4f= vec4f( #ifndef UNLIT #ifdef REFLECTION finalIrradiance + #endif #ifdef SPECULARTERM finalSpecularScaled + #endif #ifdef SHEEN finalSheenScaled + #endif #ifdef CLEARCOAT finalClearCoatScaled + #endif #ifdef REFLECTION finalRadianceScaled + #if defined(SHEEN) && defined(ENVIRONMENTBRDF) sheenOut.finalSheenRadianceScaled + #endif #ifdef CLEARCOAT clearcoatOut.finalClearCoatRadianceScaled + #endif #endif #ifdef SS_REFRACTION subSurfaceOut.finalRefraction + #endif #endif finalAmbient + finalDiffuse, alpha); #ifdef LIGHTMAP #ifndef LIGHTMAPEXCLUDED #ifdef USELIGHTMAPASSHADOWMAP finalColor=vec4f(finalColor.rgb*lightmapColor.rgb,finalColor.a); #else finalColor=vec4f(finalColor.rgb+lightmapColor.rgb,finalColor.a); #endif #endif #endif finalColor=vec4f(finalColor.rgb+finalEmissive,finalColor.a); #define CUSTOM_FRAGMENT_BEFORE_FOG finalColor=max(finalColor,vec4f(0.0)); `;de.IncludesShadersStoreWGSL[tSt]=iSt;const rSt="pbrBlockImageProcessing",sSt=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) #if !defined(SKIPFINALCOLORCLAMP) finalColor=vec4f(clamp(finalColor.rgb,vec3f(0.),vec3f(30.0)),finalColor.a); #endif #else finalColor=applyImageProcessing(finalColor); #endif finalColor=vec4f(finalColor.rgb,finalColor.a*mesh.visibility); #ifdef PREMULTIPLYALPHA finalColor=vec4f(finalColor.rgb*finalColor.a,finalColor.a);; #endif `;de.IncludesShadersStoreWGSL[rSt]=sSt;const nSt="oitFragment",aSt=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY var fragDepth: f32=fragmentInputs.position.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS var halfFloat: i32=packHalf2x16( vec2f(fragDepth));var full: vec2f=unpackHalf2x16(halfFloat);fragDepth=full.x; #endif var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var lastDepth: vec2f=textureLoad(oitDepthSampler,fragCoord,0).rg;var lastFrontColor: vec4f=textureLoad(oitFrontColorSampler,fragCoord,0);fragmentOutputs.depth=vec2f(-MAX_DEPTH);fragmentOutputs.frontColor=lastFrontColor;fragmentOutputs.backColor= vec4f(0.0); #ifdef USE_REVERSE_DEPTHBUFFER var furthestDepth: f32=-lastDepth.x;var nearestDepth: f32=lastDepth.y; #else var nearestDepth: f32=-lastDepth.x;var furthestDepth: f32=lastDepth.y; #endif var alphaMultiplier: f32=1.0-lastFrontColor.a; #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepth>nearestDepth || fragDepthfurthestDepth) { #endif return fragmentOutputs;} #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepthfurthestDepth) { #else if (fragDepth>nearestDepth && fragDepth0 if (input.vClipSpacePosition.x/input.vClipSpacePosition.w>=uniforms.vDebugMode.x) {var color: vec3f; #if DEBUGMODE==1 color=fragmentInputs.vPositionW.rgb; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==2 && defined(NORMAL) color=fragmentInputs.vNormalW.rgb; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) color=TBN[0]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) color=TBN[1]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==5 color=normalW; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==6 && defined(MAINUV1) color= vec3f(input.vMainUV1,0.0); #elif DEBUGMODE==7 && defined(MAINUV2) color= vec3f(input.vMainUV2,0.0); #elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) color=clearcoatOut.TBNClearCoat[0]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) color=clearcoatOut.TBNClearCoat[1]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==10 && defined(CLEARCOAT) color=clearcoatOut.clearCoatNormalW; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==11 && defined(ANISOTROPIC) color=anisotropicOut.anisotropicNormal; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==12 && defined(ANISOTROPIC) color=anisotropicOut.anisotropicTangent; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==13 && defined(ANISOTROPIC) color=anisotropicOut.anisotropicBitangent; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==20 && defined(ALBEDO) color=albedoTexture.rgb; #ifndef GAMMAALBEDO #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==21 && defined(AMBIENT) color=aoOut.ambientOcclusionColorMap.rgb; #elif DEBUGMODE==22 && defined(OPACITY) color=opacityMap.rgb; #elif DEBUGMODE==23 && defined(EMISSIVE) color=emissiveColorTex.rgb; #ifndef GAMMAEMISSIVE #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==24 && defined(LIGHTMAP) color=lightmapColor; #ifndef GAMMALIGHTMAP #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) color=reflectivityOut.surfaceMetallicColorMap.rgb; #elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) color=reflectivityOut.surfaceReflectivityColorMap.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) color= vec3f(clearcoatOut.clearCoatMapData.rg,0.0); #elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) color=clearcoatOut.clearCoatTintMapData.rgb; #elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) color=sheenOut.sheenMapData.rgb; #elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) color=anisotropicOut.anisotropyMapData.rgb; #elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) color=subSurfaceOut.thicknessMap.rgb; #elif DEBUGMODE==32 && defined(BUMP) color=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).rgb; #elif DEBUGMODE==40 && defined(SS_REFRACTION) color=subSurfaceOut.environmentRefraction.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==41 && defined(REFLECTION) color=reflectionOut.environmentRadiance.rgb; #ifndef GAMMAREFLECTION #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) color=clearcoatOut.environmentClearCoatRadiance.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==50 color=diffuseBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==51 && defined(SPECULARTERM) color=specularBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==52 && defined(CLEARCOAT) color=clearCoatBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==53 && defined(SHEEN) color=sheenBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==54 && defined(REFLECTION) color=reflectionOut.environmentIrradiance.rgb; #ifndef GAMMAREFLECTION #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==60 color=surfaceAlbedo.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==61 color=clearcoatOut.specularEnvironmentR0; #define DEBUGMODE_GAMMA #elif DEBUGMODE==62 && defined(METALLICWORKFLOW) color= vec3f(reflectivityOut.metallicRoughness.r); #elif DEBUGMODE==71 && defined(METALLICWORKFLOW) color=reflectivityOut.metallicF0; #elif DEBUGMODE==63 color= vec3f(roughness); #elif DEBUGMODE==64 color= vec3f(alphaG); #elif DEBUGMODE==65 color= vec3f(NdotV); #elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) color=clearcoatOut.clearCoatColor; #define DEBUGMODE_GAMMA #elif DEBUGMODE==67 && defined(CLEARCOAT) color= vec3f(clearcoatOut.clearCoatRoughness); #elif DEBUGMODE==68 && defined(CLEARCOAT) color= vec3f(clearcoatOut.clearCoatNdotV); #elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) color=subSurfaceOut.transmittance; #elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) color=subSurfaceOut.refractionTransmittance; #elif DEBUGMODE==72 color= vec3f(microSurface); #elif DEBUGMODE==73 color=uniforms.vAlbedoColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) color=uniforms.vReflectivityColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==75 color=uniforms.vEmissiveColor; #define DEBUGMODE_GAMMA #elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) color= vec3f(seo); #elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) color= vec3f(eho); #elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) color= vec3f(energyConservationFactor); #elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) color=specularEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) color=clearcoatOut.clearCoatEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) color=sheenOut.sheenEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==86 && defined(ALPHABLEND) color= vec3f(luminanceOverAlpha); #elif DEBUGMODE==87 color= vec3f(alpha); #elif DEBUGMODE==88 && defined(ALBEDO) color= vec3f(albedoTexture.a); #elif DEBUGMODE==89 color=aoOut.ambientOcclusionColor; #else var stripeWidth: f32=30.;var stripePos: f32=abs(floor(input.position.x/stripeWidth));var whichColor: f32=((stripePos)%(2.));var color1: vec3f= vec3f(.6,.2,.2);var color2: vec3f= vec3f(.3,.1,.1);color=mix(color1,color2,whichColor); #endif color*=uniforms.vDebugMode.y; #ifdef DEBUGMODE_NORMALIZE color=normalize(color)*0.5+0.5; #endif #ifdef DEBUGMODE_GAMMA color=toGammaSpaceVec3(color); #endif fragmentOutputs.color=vec4f(color,1.0); #ifdef PREPASS fragmentOutputs.fragData0=toLinearSpaceVec3(color); fragmentOutputs.fragData1=vec4f(0.,0.,0.,0.); #endif #ifdef DEBUGMODE_FORCERETURN return fragmentOutputs; #endif } #endif `;de.IncludesShadersStoreWGSL[oSt]=lSt;const QWe="pbrPixelShader",$We=`#define CUSTOM_FRAGMENT_BEGIN #include[SCENE_MRT_COUNT] #include #ifndef FROMLINEARSPACE #define FROMLINEARSPACE #endif #include #include #include[0..maxSimultaneousLights] #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef REFLECTION #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS #include #include #include #include #include #include #include #include #include #include @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #include #include #include var albedoOpacityOut: albedoOpacityOutParams; #ifdef ALBEDO var albedoTexture: vec4f=textureSample(albedoSampler,albedoSamplerSampler,fragmentInputs.vAlbedoUV+uvOffset); #endif #ifdef OPACITY var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset); #endif #ifdef DECAL var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset); #endif albedoOpacityOut=albedoOpacityBlock( uniforms.vAlbedoColor #ifdef ALBEDO ,albedoTexture ,uniforms.vAlbedoInfos #endif #ifdef OPACITY ,opacityMap ,uniforms.vOpacityInfos #endif #ifdef DETAIL ,detailColor ,uniforms.vDetailInfos #endif #ifdef DECAL ,decalColor ,uniforms.vDecalInfos #endif );var surfaceAlbedo: vec3f=albedoOpacityOut.surfaceAlbedo;var alpha: f32=albedoOpacityOut.alpha; #define CUSTOM_FRAGMENT_UPDATE_ALPHA #include #define CUSTOM_FRAGMENT_BEFORE_LIGHTS var aoOut: ambientOcclusionOutParams; #ifdef AMBIENT var ambientOcclusionColorMap: vec3f=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb; #endif aoOut=ambientOcclusionBlock( #ifdef AMBIENT ambientOcclusionColorMap, uniforms.vAmbientInfos #endif ); #include #ifdef UNLIT var diffuseBase: vec3f= vec3f(1.,1.,1.); #else var baseColor: vec3f=surfaceAlbedo;var reflectivityOut: reflectivityOutParams; #if defined(REFLECTIVITY) var surfaceMetallicOrReflectivityColorMap: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,fragmentInputs.vReflectivityUV+uvOffset);var baseReflectivity: vec4f=surfaceMetallicOrReflectivityColorMap; #ifndef METALLICWORKFLOW #ifdef REFLECTIVITY_GAMMA surfaceMetallicOrReflectivityColorMap=toLinearSpaceVec4(surfaceMetallicOrReflectivityColorMap); #endif surfaceMetallicOrReflectivityColorMap=vec4f(surfaceMetallicOrReflectivityColorMap.rgb*uniforms.vReflectivityInfos.y,surfaceMetallicOrReflectivityColorMap.a); #endif #endif #if defined(MICROSURFACEMAP) var microSurfaceTexel: vec4f=textureSample(microSurfaceSampler,microSurfaceSamplerSampler,fragmentInputs.vMicroSurfaceSamplerUV+uvOffset)*uniforms.vMicroSurfaceSamplerInfos.y; #endif #ifdef METALLICWORKFLOW var metallicReflectanceFactors: vec4f=uniforms.vMetallicReflectanceFactors; #ifdef REFLECTANCE var reflectanceFactorsMap: vec4f=textureSample(reflectanceSampler,reflectanceSamplerSampler,fragmentInputs.vReflectanceUV+uvOffset); #ifdef REFLECTANCE_GAMMA reflectanceFactorsMap=toLinearSpaceVec4(reflectanceFactorsMap); #endif metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a); #endif #ifdef METALLIC_REFLECTANCE var metallicReflectanceFactorsMap: vec4f=textureSample(metallicReflectanceSampler,metallicReflectanceSamplerSampler,fragmentInputs.vMetallicReflectanceUV+uvOffset); #ifdef METALLIC_REFLECTANCE_GAMMA metallicReflectanceFactorsMap=toLinearSpaceVec4(metallicReflectanceFactorsMap); #endif #ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a); #endif metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; #endif #endif reflectivityOut=reflectivityBlock( uniforms.vReflectivityColor #ifdef METALLICWORKFLOW ,surfaceAlbedo ,metallicReflectanceFactors #endif #ifdef REFLECTIVITY ,uniforms.vReflectivityInfos ,surfaceMetallicOrReflectivityColorMap #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) ,aoOut.ambientOcclusionColor #endif #ifdef MICROSURFACEMAP ,microSurfaceTexel #endif #ifdef DETAIL ,detailColor ,uniforms.vDetailInfos #endif );var microSurface: f32=reflectivityOut.microSurface;var roughness: f32=reflectivityOut.roughness; #ifdef METALLICWORKFLOW surfaceAlbedo=reflectivityOut.surfaceAlbedo; #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; #endif #ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) var alphaFresnelOut: alphaFresnelOutParams;alphaFresnelOut=alphaFresnelBlock( normalW, viewDirectionW, alpha, microSurface );alpha=alphaFresnelOut.alpha; #endif #endif #include #ifdef ANISOTROPIC var anisotropicOut: anisotropicOutParams; #ifdef ANISOTROPIC_TEXTURE var anisotropyMapData: vec3f=textureSample(anisotropySampler,anisotropySamplerSampler,fragmentInputs.vAnisotropyUV+uvOffset).rgb*uniforms.vAnisotropyInfos.y; #endif anisotropicOut=anisotropicBlock( uniforms.vAnisotropy, roughness, #ifdef ANISOTROPIC_TEXTURE anisotropyMapData, #endif TBN, normalW, viewDirectionW ); #endif #ifdef REFLECTION var reflectionOut: reflectionOutParams; #ifndef USE_CUSTOM_REFLECTION reflectionOut=reflectionBlock( input.vPositionW ,normalW ,alphaG ,uniforms.vReflectionMicrosurfaceInfos ,uniforms.vReflectionInfos ,uniforms.vReflectionColor #ifdef ANISOTROPIC ,anisotropicOut #endif #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,NdotVUnclamped #endif #ifdef LINEARSPECULARREFLECTION ,roughness #endif ,reflectionSampler ,reflectionSamplerSampler #if defined(NORMAL) && defined(USESPHERICALINVERTEX) ,input.vEnvironmentIrradiance #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,uniforms.reflectionMatrix #endif #endif #ifdef USEIRRADIANCEMAP ,irradianceSampler ,irradianceSamplerSampler #endif #ifndef LODBASEDMICROSFURACE ,reflectionLowSampler ,reflectionLowSamplerSampler ,reflectionHighSampler ,reflectionHighSamplerSampler #endif #ifdef REALTIME_FILTERING ,uniforms.vReflectionFilteringInfo #endif ); #else #define CUSTOM_REFLECTION #endif #endif #include #ifdef SHEEN var sheenOut: sheenOutParams; #ifdef SHEEN_TEXTURE var sheenMapData: vec4f=textureSample(sheenSampler,sheenSamplerSampler,fragmentInputs.vSheenUV+uvOffset); #endif #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) var sheenMapRoughnessData: vec4f=textureSample(sheenRoughnessSampler,sheenRoughnessSamplerSampler,fragmentInputs.vSheenRoughnessUV+uvOffset)*uniforms.vSheenInfos.w; #endif sheenOut=sheenBlock( uniforms.vSheenColor #ifdef SHEEN_ROUGHNESS ,uniforms.vSheenRoughness #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) ,sheenMapRoughnessData #endif #endif ,roughness #ifdef SHEEN_TEXTURE ,sheenMapData ,uniforms.vSheenInfos.y #endif ,reflectance #ifdef SHEEN_LINKWITHALBEDO ,baseColor ,surfaceAlbedo #endif #ifdef ENVIRONMENTBRDF ,NdotV ,environmentBrdf #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) ,AARoughnessFactors ,uniforms.vReflectionMicrosurfaceInfos ,uniforms.vReflectionInfos ,uniforms.vReflectionColor ,uniforms.vLightingIntensity ,reflectionSampler ,reflectionSamplerSampler ,reflectionOut.reflectionCoords ,NdotVUnclamped #ifndef LODBASEDMICROSFURACE ,reflectionLowSampler ,reflectionLowSamplerSampler ,reflectionHighSampler ,reflectionHighSamplerSampler #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) ,seo #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) ,eho #endif #endif ); #ifdef SHEEN_LINKWITHALBEDO surfaceAlbedo=sheenOut.surfaceAlbedo; #endif #endif #ifdef CLEARCOAT #ifdef CLEARCOAT_TEXTURE var clearCoatMapData: vec2f=textureSample(clearCoatSampler,clearCoatSamplerSampler,fragmentInputs.vClearCoatUV+uvOffset).rg*uniforms.vClearCoatInfos.y; #endif #endif #ifdef IRIDESCENCE var iridescenceOut: iridescenceOutParams; #ifdef IRIDESCENCE_TEXTURE var iridescenceMapData: vec2f=textureSample(iridescenceSampler,iridescenceSamplerSampler,fragmentInputs.vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE var iridescenceThicknessMapData: vec2f=textureSample(iridescenceThicknessSampler,iridescenceThicknessSamplerSampler,fragmentInputs.vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; #endif iridescenceOut=iridescenceBlock( uniforms.vIridescenceParams ,NdotV ,specularEnvironmentR0 #ifdef IRIDESCENCE_TEXTURE ,iridescenceMapData #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE ,iridescenceThicknessMapData #endif #ifdef CLEARCOAT ,NdotVUnclamped #ifdef CLEARCOAT_TEXTURE ,clearCoatMapData #endif #endif );var iridescenceIntensity: f32=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; #endif var clearcoatOut: clearcoatOutParams; #ifdef CLEARCOAT #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) var clearCoatMapRoughnessData: vec4f=textureSample(clearCoatRoughnessSampler,clearCoatRoughnessSamplerSampler,fragmentInputs.vClearCoatRoughnessUV+uvOffset)*uniforms.vClearCoatInfos.w; #endif #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) var clearCoatTintMapData: vec4f=textureSample(clearCoatTintSampler,clearCoatTintSamplerSampler,fragmentInputs.vClearCoatTintUV+uvOffset); #endif #ifdef CLEARCOAT_BUMP var clearCoatBumpMapData: vec4f=textureSample(clearCoatBumpSampler,clearCoatBumpSamplerSampler,fragmentInputs.vClearCoatBumpUV+uvOffset); #endif clearcoatOut=clearcoatBlock( input.vPositionW ,geometricNormalW ,viewDirectionW ,uniforms.vClearCoatParams #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) ,clearCoatMapRoughnessData #endif ,specularEnvironmentR0 #ifdef CLEARCOAT_TEXTURE ,clearCoatMapData #endif #ifdef CLEARCOAT_TINT ,uniforms.vClearCoatTintParams ,uniforms.clearCoatColorAtDistance ,uniforms.vClearCoatRefractionParams #ifdef CLEARCOAT_TINT_TEXTURE ,clearCoatTintMapData #endif #endif #ifdef CLEARCOAT_BUMP ,uniforms.vClearCoatBumpInfos ,clearCoatBumpMapData ,fragmentInputs.vClearCoatBumpUV #if defined(TANGENT) && defined(NORMAL) ,vTBN #else ,uniforms.vClearCoatTangentSpaceParams #endif #ifdef OBJECTSPACE_NORMALMAP ,uniforms.normalMatrix #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) ,faceNormal #endif #ifdef REFLECTION ,uniforms.vReflectionMicrosurfaceInfos ,uniforms.vReflectionInfos ,uniforms.vReflectionColor ,uniforms.vLightingIntensity ,reflectionSampler ,reflectionSamplerSampler #ifndef LODBASEDMICROSFURACE ,reflectionLowSampler ,reflectionLowSamplerSampler ,reflectionHighSampler ,reflectionHighSamplerSampler #endif #ifdef REALTIME_FILTERING ,uniforms.vReflectionFilteringInfo #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION ,ambientMonochrome #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) ,select(-1.,1.,fragmentInputs.frontFacing) #endif ); #else clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; #endif #include var subSurfaceOut: subSurfaceOutParams; #ifdef SUBSURFACE #ifdef SS_THICKNESSANDMASK_TEXTURE var thicknessMap: vec4f=textureSample(thicknessSampler,thicknessSamplerSampler,fragmentInputs.vThicknessUV+uvOffset); #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE var refractionIntensityMap: vec4f=textureSample(refractionIntensitySampler,refractionIntensitySamplerSampler,fragmentInputs.vRefractionIntensityUV+uvOffset); #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE var translucencyIntensityMap: vec4f=textureSample(translucencyIntensitySampler,translucencyIntensitySamplerSampler,fragmentInputs.vTranslucencyIntensityUV+uvOffset); #endif #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE var translucencyColorMap: vec4f=textureSample(translucencyColorSampler,translucencyColorSamplerSampler,fragmentInputs.vTranslucencyColorUV+uvOffset); #endif subSurfaceOut=subSurfaceBlock( uniforms.vSubSurfaceIntensity ,uniforms.vThicknessParam ,uniforms.vTintColor ,normalW ,specularEnvironmentReflectance #ifdef SS_THICKNESSANDMASK_TEXTURE ,thicknessMap #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE ,refractionIntensityMap #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE ,translucencyIntensityMap #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY ,uniforms.reflectionMatrix #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,reflectionOut.irradianceVector #endif #if defined(REALTIME_FILTERING) ,reflectionSampler ,reflectionSamplerSampler ,vReflectionFilteringInfo #endif #endif #ifdef USEIRRADIANCEMAP ,irradianceSampler ,irradianceSamplerSampler #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) ,surfaceAlbedo #endif #ifdef SS_REFRACTION ,input.vPositionW ,viewDirectionW ,scene.view ,uniforms.vRefractionInfos ,uniforms.refractionMatrix ,uniforms.vRefractionMicrosurfaceInfos ,uniforms.vLightingIntensity #ifdef SS_LINKREFRACTIONTOTRANSPARENCY ,alpha #endif #ifdef SS_LODINREFRACTIONALPHA ,NdotVUnclamped #endif #ifdef SS_LINEARSPECULARREFRACTION ,roughness #endif ,alphaG ,refractionSampler ,refractionSamplerSampler #ifndef LODBASEDMICROSFURACE ,refractionLowSampler ,refractionLowSamplerSampler ,refractionHighSampler ,refractionHighSamplerSampler #endif #ifdef ANISOTROPIC ,anisotropicOut #endif #ifdef REALTIME_FILTERING ,uniforms.vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,uniforms.vRefractionPosition ,uniforms.vRefractionSize #endif #ifdef SS_DISPERSION ,dispersion #endif #endif #ifdef SS_TRANSLUCENCY ,uniforms.vDiffusionDistance ,uniforms.vTranslucencyColor #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE ,translucencyColorMap #endif #endif ); #ifdef SS_REFRACTION surfaceAlbedo=subSurfaceOut.surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha=subSurfaceOut.alpha; #endif #endif #else subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; #endif #include #include[0..maxSimultaneousLights] #include #endif #include #define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION #include #include #include(color,finalColor) #include #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>0.4);var fragData: array,SCENE_MRT_COUNT>; #ifdef PREPASS_POSITION fragData[PREPASS_POSITION_INDEX]= vec4f(input.vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO_SQRT var sqAlbedo: vec3f=sqrt(surfaceAlbedo); #endif #ifdef PREPASS_IRRADIANCE var irradiance: vec3f=finalDiffuse; #ifndef UNLIT #ifdef REFLECTION irradiance+=finalIrradiance; #endif #endif #ifdef SS_SCATTERING fragData[0]= vec4f(finalColor.rgb-irradiance,finalColor.a); irradiance/=sqAlbedo; #else fragData[0]=finalColor; var scatteringDiffusionProfile: f32=255.; #endif fragData[PREPASS_IRRADIANCE_INDEX]= vec4f(clamp(irradiance, vec3f(0.), vec3f(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); #else fragData[0]= vec4f(finalColor.rgb,finalColor.a); #endif #ifdef PREPASS_DEPTH fragData[PREPASS_DEPTH_INDEX]= vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE fragData[PREPASS_NORMAL_INDEX]= vec4f(normalW,writeGeometryInfo); #else fragData[PREPASS_NORMAL_INDEX]= vec4f(normalize((scene.view* vec4f(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_ALBEDO_SQRT fragData[PREPASS_ALBEDO_SQRT_INDEX]= vec4f(sqAlbedo,writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #ifndef UNLIT fragData[PREPASS_REFLECTIVITY_INDEX]= vec4f(specularEnvironmentR0,microSurface)*writeGeometryInfo; #else fragData[PREPASS_REFLECTIVITY_INDEX]= vec4f( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; #endif #endif #if SCENE_MRT_COUNT>0 fragmentOutputs.fragData0= fragData[0]; #endif #if SCENE_MRT_COUNT>1 fragmentOutputs.fragData1= fragData[1]; #endif #if SCENE_MRT_COUNT>2 fragmentOutputs.fragData2= fragData[2]; #endif #if SCENE_MRT_COUNT>3 fragmentOutputs.fragData3= fragData[3]; #endif #if SCENE_MRT_COUNT>4 fragmentOutputs.fragData4= fragData[4]; #endif #if SCENE_MRT_COUNT>5 fragmentOutputs.fragData5= fragData[5]; #endif #if SCENE_MRT_COUNT>6 fragmentOutputs.fragData6= fragData[6]; #endif #if SCENE_MRT_COUNT>7 fragmentOutputs.fragData7= fragData[7]; #endif #endif #if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) fragmentOutputs.color=finalColor; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+finalColor.rgb*finalColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-finalColor.a));} else {fragmentOutputs.backColor+=finalColor;} #endif #include #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStoreWGSL[QWe]=$We;const ZWe={name:QWe,shader:$We},qWe=Object.freeze(Object.defineProperty({__proto__:null,pbrPixelShaderWGSL:ZWe},Symbol.toStringTag,{value:"Module"})),cSt="decalVertexDeclaration",uSt=`#ifdef DECAL uniform vec4 vDecalInfos;uniform mat4 decalMatrix; #endif `;de.IncludesShadersStore[cSt]=uSt;const hSt="pbrVertexDeclaration",dSt=`uniform mat4 view;uniform mat4 viewProjection; #ifdef ALBEDO uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; #endif #ifdef AMBIENT uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; #endif #ifdef OPACITY uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; #endif #ifdef REFLECTIVITY uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; #endif #ifdef METALLIC_REFLECTANCE uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; #endif #ifdef REFLECTANCE uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; #endif #ifdef MICROSURFACEMAP uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; #endif #ifdef POINTSIZE uniform float pointSize; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; #endif #ifdef CLEARCOAT #if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) uniform vec4 vClearCoatInfos; #endif #ifdef CLEARCOAT_TEXTURE uniform mat4 clearCoatMatrix; #endif #ifdef CLEARCOAT_TEXTURE_ROUGHNESS uniform mat4 clearCoatRoughnessMatrix; #endif #ifdef CLEARCOAT_BUMP uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; #endif #ifdef CLEARCOAT_TINT_TEXTURE uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; #endif #endif #ifdef IRIDESCENCE #if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) uniform vec4 vIridescenceInfos; #endif #ifdef IRIDESCENCE_TEXTURE uniform mat4 iridescenceMatrix; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE uniform mat4 iridescenceThicknessMatrix; #endif #endif #ifdef ANISOTROPIC #ifdef ANISOTROPIC_TEXTURE uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; #endif #endif #ifdef SHEEN #if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) uniform vec4 vSheenInfos; #endif #ifdef SHEEN_TEXTURE uniform mat4 sheenMatrix; #endif #ifdef SHEEN_TEXTURE_ROUGHNESS uniform mat4 sheenRoughnessMatrix; #endif #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; #endif #ifdef SS_THICKNESSANDMASK_TEXTURE uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; #endif #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix; #endif #endif #ifdef NORMAL #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) #ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; #else uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; #endif #endif #endif #endif #ifdef DETAIL uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION `;de.IncludesShadersStore[hSt]=dSt;const fSt="pbrUboDeclaration",pSt=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; #define ADDITIONAL_UBO_DECLARATION }; #include #include `;de.IncludesShadersStore[fSt]=pSt;const mSt="uvAttributeDeclaration",gSt=`#ifdef UV{X} attribute vec2 uv{X}; #endif `;de.IncludesShadersStore[mSt]=gSt;const _St="mainUVVaryingDeclaration",vSt=`#ifdef MAINUV{X} varying vec2 vMainUV{X}; #endif `;de.IncludesShadersStore[_St]=vSt;const ySt="prePassVertexDeclaration",xSt=`#ifdef PREPASS #ifdef PREPASS_DEPTH varying vec3 vViewPos; #endif #ifdef PREPASS_VELOCITY uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #endif `;de.IncludesShadersStore[ySt]=xSt;const ASt="samplerVertexDeclaration",bSt=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying vec2 v_VARYINGNAME_UV; #endif `;de.IncludesShadersStore[ASt]=bSt;const CSt="harmonicsFunctions",SSt=`#ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 + vSphericalL1_1*(normal.y) + vSphericalL10*(normal.z) + vSphericalL11*(normal.x) + vSphericalL2_2*(normal.y*normal.x) + vSphericalL2_1*(normal.y*normal.z) + vSphericalL20*((3.0*normal.z*normal.z)-1.0) + vSphericalL21*(normal.z*normal.x) + vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} #else vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} #endif #endif `;de.IncludesShadersStore[CSt]=SSt;const ESt="bumpVertexDeclaration",TSt=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif `;de.IncludesShadersStore[ESt]=TSt;const MSt="prePassVertex",RSt=`#ifdef PREPASS_DEPTH vViewPos=(view*worldPos).rgb; #endif #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*worldPos; #if NUM_BONE_INFLUENCERS>0 mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); #else vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif `;de.IncludesShadersStore[MSt]=RSt;const ISt="uvVariableDeclaration",PSt=`#if !defined(UV{X}) && defined(MAINUV{X}) vec2 uv{X}=vec2(0.,0.); #endif #ifdef MAINUV{X} vMainUV{X}=uv{X}; #endif `;de.IncludesShadersStore[ISt]=PSt;const wSt="samplerVertexImplementation",DSt=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (v_INFONAME_==0.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} #ifdef UV2 else if (v_INFONAME_==1.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} #endif #ifdef UV3 else if (v_INFONAME_==2.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} #endif #ifdef UV4 else if (v_INFONAME_==3.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} #endif #ifdef UV5 else if (v_INFONAME_==4.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} #endif #ifdef UV6 else if (v_INFONAME_==5.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} #endif #endif `;de.IncludesShadersStore[wSt]=DSt;const LSt="bumpVertex",OSt=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); #endif #endif `;de.IncludesShadersStore[LSt]=OSt;const JWe="pbrVertexShader",eKe=`precision highp float; #include<__decl__pbrVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #ifdef TANGENT attribute vec4 tangent; #endif #ifdef UV1 attribute vec2 uv; #endif #include[2..7] #include[1..7] #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #include #include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) #endif #ifdef SUBSURFACE #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor) #endif varying vec3 vPositionW; #if DEBUGMODE>0 varying vec4 vClipSpacePosition; #endif #ifdef NORMAL varying vec3 vNormalW; #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) varying vec3 vEnvironmentIrradiance; #include #endif #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #ifdef NORMAL vec3 normalUpdated=normal; #endif #ifdef TANGENT vec4 tangentUpdated=tangent; #endif #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); #include #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normalUpdated); #endif #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif #if DEBUGMODE>0 vClipSpacePosition=gl_Position; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); #endif #ifndef UV1 vec2 uvUpdated=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uvUpdated; #endif #include[2..7] #include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z) #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) #endif #ifdef SUBSURFACE #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) #include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x) #endif #include #include #include #include[0..maxSimultaneousLights] #include #if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[JWe]=eKe;const tKe={name:JWe,shader:eKe},iKe=Object.freeze(Object.defineProperty({__proto__:null,pbrVertexShader:tKe},Symbol.toStringTag,{value:"Module"})),NSt="prePassDeclaration",FSt=`#ifdef PREPASS #extension GL_EXT_draw_buffers : require layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; #ifdef PREPASS_DEPTH varying highp vec3 vViewPos; #endif #ifdef PREPASS_VELOCITY varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; #endif #endif `;de.IncludesShadersStore[NSt]=FSt;const BSt="oitDeclaration",kSt=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY #extension GL_EXT_draw_buffers : require layout(location=0) out vec2 depth; layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; #define MAX_DEPTH 99999.0 highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; #endif `;de.IncludesShadersStore[BSt]=kSt;const USt="decalFragmentDeclaration",zSt=`#ifdef DECAL uniform vec4 vDecalInfos; #endif `;de.IncludesShadersStore[USt]=zSt;const VSt="pbrFragmentDeclaration",GSt=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; #ifdef ALBEDO uniform vec2 vAlbedoInfos; #endif #ifdef AMBIENT uniform vec4 vAmbientInfos; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #ifdef OPACITY uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos; #endif #ifdef REFLECTIVITY uniform vec3 vReflectivityInfos; #endif #ifdef MICROSURFACEMAP uniform vec2 vMicroSurfaceSamplerInfos; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) uniform mat4 view; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos; #ifdef REALTIME_FILTERING uniform vec2 vReflectionFilteringInfo; #endif uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif #if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; #endif #ifdef CLEARCOAT uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; #if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) uniform vec4 vClearCoatInfos; #endif #ifdef CLEARCOAT_TEXTURE uniform mat4 clearCoatMatrix; #endif #ifdef CLEARCOAT_TEXTURE_ROUGHNESS uniform mat4 clearCoatRoughnessMatrix; #endif #ifdef CLEARCOAT_BUMP uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; #endif #ifdef CLEARCOAT_TINT uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; #ifdef CLEARCOAT_TINT_TEXTURE uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; #endif #endif #endif #ifdef IRIDESCENCE uniform vec4 vIridescenceParams; #if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) uniform vec4 vIridescenceInfos; #endif #ifdef IRIDESCENCE_TEXTURE uniform mat4 iridescenceMatrix; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE uniform mat4 iridescenceThicknessMatrix; #endif #endif #ifdef ANISOTROPIC uniform vec3 vAnisotropy; #ifdef ANISOTROPIC_TEXTURE uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; #endif #endif #ifdef SHEEN uniform vec4 vSheenColor; #ifdef SHEEN_ROUGHNESS uniform float vSheenRoughness; #endif #if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) uniform vec4 vSheenInfos; #endif #ifdef SHEEN_TEXTURE uniform mat4 sheenMatrix; #endif #ifdef SHEEN_TEXTURE_ROUGHNESS uniform mat4 sheenRoughnessMatrix; #endif #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; #ifdef REALTIME_FILTERING uniform vec2 vRefractionFilteringInfo; #endif #ifdef SS_DISPERSION uniform float dispersion; #endif #endif #ifdef SS_THICKNESSANDMASK_TEXTURE uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; #endif uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor; #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix; #endif #endif #ifdef PREPASS #ifdef SS_SCATTERING uniform float scatteringDiffusionProfile; #endif #endif #if DEBUGMODE>0 uniform vec2 vDebugMode; #endif #ifdef DETAIL uniform vec4 vDetailInfos; #endif #include #ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; #else uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; #endif #endif #define ADDITIONAL_FRAGMENT_DECLARATION `;de.IncludesShadersStore[VSt]=GSt;const WSt="pbrFragmentExtraDeclaration",KSt=`varying vec3 vPositionW; #if DEBUGMODE>0 varying vec4 vClipSpacePosition; #endif #include[1..7] #ifdef NORMAL varying vec3 vNormalW; #if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) varying vec3 vEnvironmentIrradiance; #endif #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif `;de.IncludesShadersStore[WSt]=KSt;const HSt="samplerFragmentDeclaration",jSt=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 #define v_VARYINGNAME_UV vMainUV2 #elif _DEFINENAME_DIRECTUV==3 #define v_VARYINGNAME_UV vMainUV3 #elif _DEFINENAME_DIRECTUV==4 #define v_VARYINGNAME_UV vMainUV4 #elif _DEFINENAME_DIRECTUV==5 #define v_VARYINGNAME_UV vMainUV5 #elif _DEFINENAME_DIRECTUV==6 #define v_VARYINGNAME_UV vMainUV6 #else varying vec2 v_VARYINGNAME_UV; #endif uniform sampler2D _SAMPLERNAME_Sampler; #endif `;de.IncludesShadersStore[HSt]=jSt;const XSt="samplerFragmentAlternateDeclaration",YSt=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 #define v_VARYINGNAME_UV vMainUV2 #elif _DEFINENAME_DIRECTUV==3 #define v_VARYINGNAME_UV vMainUV3 #elif _DEFINENAME_DIRECTUV==4 #define v_VARYINGNAME_UV vMainUV4 #elif _DEFINENAME_DIRECTUV==5 #define v_VARYINGNAME_UV vMainUV5 #elif _DEFINENAME_DIRECTUV==6 #define v_VARYINGNAME_UV vMainUV6 #else varying vec2 v_VARYINGNAME_UV; #endif #endif `;de.IncludesShadersStore[XSt]=YSt;const QSt="pbrFragmentSamplersDeclaration",$St=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) #include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) #include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) #include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef CLEARCOAT #include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) #include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) uniform sampler2D clearCoatRoughnessSampler; #endif #include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) #include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) #endif #ifdef IRIDESCENCE #include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) #include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) #endif #ifdef SHEEN #include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) #include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) uniform sampler2D sheenRoughnessSampler; #endif #endif #ifdef ANISOTROPIC #include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) #endif #ifdef REFLECTION #ifdef REFLECTIONMAP_3D #define sampleReflection(s,c) textureCube(s,c) uniform samplerCube reflectionSampler; #ifdef LODBASEDMICROSFURACE #define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) #else uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; #endif #ifdef USEIRRADIANCEMAP uniform samplerCube irradianceSampler; #endif #else #define sampleReflection(s,c) texture2D(s,c) uniform sampler2D reflectionSampler; #ifdef LODBASEDMICROSFURACE #define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) #else uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; #endif #ifdef USEIRRADIANCEMAP uniform sampler2D irradianceSampler; #endif #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #endif #ifdef ENVIRONMENTBRDF uniform sampler2D environmentBrdfSampler; #endif #ifdef SUBSURFACE #ifdef SS_REFRACTION #ifdef SS_REFRACTIONMAP_3D #define sampleRefraction(s,c) textureCube(s,c) uniform samplerCube refractionSampler; #ifdef LODBASEDMICROSFURACE #define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) #else uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; #endif #else #define sampleRefraction(s,c) texture2D(s,c) uniform sampler2D refractionSampler; #ifdef LODBASEDMICROSFURACE #define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) #else uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; #endif #endif #endif #include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor) #endif `;de.IncludesShadersStore[QSt]=$St;const ZSt="subSurfaceScatteringFunctions",qSt=`bool testLightingForSSS(float diffusionProfile) {return diffusionProfile<1.;}`;de.IncludesShadersStore[ZSt]=qSt;const JSt="pbrHelperFunctions",e6t=`#define MINIMUMVARIANCE 0.0005 float convertRoughnessToAverageSlope(float roughness) {return square(roughness)+MINIMUMVARIANCE;} float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} vec2 getAARoughnessFactors(vec3 normalVector) { #ifdef SPECULARAA vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); #else return vec2(0.); #endif } #ifdef ANISOTROPIC #ifdef ANISOTROPIC_LEGACY vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} #else vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} #endif #endif #if defined(CLEARCOAT) || defined(SS_REFRACTION) vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), clearCoatIntensity);return clearCoatAbsorption;} #endif #ifdef MICROSURFACEAUTOMATIC float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) {const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} #endif `;de.IncludesShadersStore[JSt]=e6t;const t6t="pbrDirectLightingSetupFunctions",i6t=`struct preLightingInfo {vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; #ifdef IRIDESCENCE float iridescenceIntensity; #endif };preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; #ifdef SPECULARTERM result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); #endif return result;}`;de.IncludesShadersStore[t6t]=i6t;const r6t="pbrDirectLightingFalloffFunctions",s6t=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) {return max(0.,1.0-length(lightOffset)/range);} float computeDistanceLightFalloff_Physical(float lightDistanceSquared) {return 1.0/maxEps(lightDistanceSquared);} float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) {float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) { #ifdef USEPHYSICALLIGHTFALLOFF return computeDistanceLightFalloff_Physical(lightDistanceSquared); #elif defined(USEGLTFLIGHTFALLOFF) return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); #else return computeDistanceLightFalloff_Standard(lightOffset,range); #endif } float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) {float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) {falloff=max(0.,pow(cosAngle,exponent));} return falloff;} float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) {const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) {float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) { #ifdef USEPHYSICALLIGHTFALLOFF return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); #elif defined(USEGLTFLIGHTFALLOFF) return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); #else return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); #endif }`;de.IncludesShadersStore[r6t]=s6t;const n6t="pbrDirectLightingFunctions",a6t=`#define CLEARCOATREFLECTANCE90 1.0 struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; #endif #ifdef CLEARCOAT vec4 clearCoat; #endif #ifdef SHEEN vec3 sheen; #endif };float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { #if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; #else return roughness; #endif } vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} #define inline vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} #ifdef SS_TRANSLUCENCY vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} #endif #ifdef SPECULARTERM vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); #ifdef IRIDESCENCE fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); #endif float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); #ifdef BRDF_V_HEIGHT_CORRELATED float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); #else float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); #endif vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} #endif #ifdef ANISOTROPIC vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); #ifdef IRIDESCENCE fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); #endif float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} #endif #ifdef CLEARCOAT vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( clearCoatTerm*info.attenuation*NccdotL*lightColor, 1.0-fresnel );} vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} #endif #ifdef SHEEN vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); #else */ float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} #endif `;de.IncludesShadersStore[n6t]=a6t;const o6t="pbrIBLFunctions",l6t=`#if defined(REFLECTION) || defined(SS_REFRACTION) float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} #endif #if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} #endif #if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} #endif #if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) #define UNPACK_LOD(x) (1.0-x)*255.0 float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} #endif `;de.IncludesShadersStore[o6t]=l6t;const rKe="bumpFragmentMainFunctions",sKe=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #ifdef OBJECTSPACE_NORMALMAP uniform mat4 normalMatrix; #if defined(WEBGL2) || defined(WEBGPU) mat4 toNormalMatrix(mat4 wMatrix) {mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;} #else mat4 toNormalMatrix(mat4 m) {float a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3], a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3], a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3], a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3], b00=a00*a11-a01*a10, b01=a00*a12-a02*a10, b02=a00*a13-a03*a10, b03=a01*a12-a02*a11, b04=a01*a13-a03*a11, b05=a02*a13-a03*a12, b06=a20*a31-a21*a30, b07=a20*a32-a22*a30, b08=a20*a33-a23*a30, b09=a21*a32-a22*a31, b10=a21*a33-a23*a31, b11=a22*a33-a23*a32, det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4( a11*b11-a12*b10+a13*b09, a02*b10-a01*b11-a03*b09, a31*b05-a32*b04+a33*b03, a22*b04-a21*b05-a23*b03, a12*b08-a10*b11-a13*b07, a00*b11-a02*b08+a03*b07, a32*b02-a30*b05-a33*b01, a20*b05-a22*b02+a23*b01, a10*b10-a11*b08+a13*b06, a01*b08-a00*b10-a03*b06, a30*b04-a31*b02+a33*b00, a21*b02-a20*b04-a23*b00, a11*b07-a10*b09-a12*b06, a00*b09-a01*b07+a02*b06, a31*b01-a30*b03-a32*b00, a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], mi[0][1],mi[1][1],mi[2][1],mi[3][1], mi[0][2],mi[1][2],mi[2][2],mi[3][2], mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} #endif #endif vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale) { #ifdef NORMALXYSCALE normal=normalize(normal*vec3(scale,scale,1.0)); #endif return normalize(cotangentFrame*normal);} vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) {return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) {vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} #endif `;de.IncludesShadersStore[rKe]=sKe;const nKe={name:rKe,shader:sKe},c6t=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentMainFunctions:nKe},Symbol.toStringTag,{value:"Module"})),aKe="bumpFragmentFunctions",oKe=`#if defined(BUMP) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) #endif #if defined(BUMP) && defined(PARALLAX) const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) {float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} else {currRayHeight-=stepSize;vLastOffset=vCurrOffset; #ifdef PARALLAX_RHS vCurrOffset-=stepSize*vMaxOffset; #else vCurrOffset+=stepSize*vMaxOffset; #endif lastSampledHeight=currSampledHeight;}} return vCurrOffset;} vec2 parallaxOffset(vec3 viewDir,float heightScale) {float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; #ifdef PARALLAX_RHS return texCoordOffset; #else return -texCoordOffset; #endif } #endif `;de.IncludesShadersStore[aKe]=oKe;const lKe={name:aKe,shader:oKe},u6t=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentFunctions:lKe},Symbol.toStringTag,{value:"Module"})),h6t="decalFragment",d6t=`#ifdef DECAL #ifdef GAMMADECAL decalColor.rgb=toLinearSpace(decalColor.rgb); #endif #ifdef DECAL_SMOOTHALPHA decalColor.a*=decalColor.a; #endif surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); #endif `;de.IncludesShadersStore[h6t]=d6t;const f6t="pbrBlockAlbedoOpacity",p6t=`struct albedoOpacityOutParams {vec3 surfaceAlbedo;float alpha;}; #define pbr_inline albedoOpacityOutParams albedoOpacityBlock( in vec4 vAlbedoColor #ifdef ALBEDO ,in vec4 albedoTexture ,in vec2 albedoInfos #endif #ifdef OPACITY ,in vec4 opacityMap ,in vec2 vOpacityInfos #endif #ifdef DETAIL ,in vec4 detailColor ,in vec4 vDetailInfos #endif #ifdef DECAL ,in vec4 decalColor ,in vec4 vDecalInfos #endif ) {albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; #ifdef ALBEDO #if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) alpha*=albedoTexture.a; #endif #ifdef GAMMAALBEDO surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); #else surfaceAlbedo*=albedoTexture.rgb; #endif surfaceAlbedo*=albedoInfos.y; #endif #ifndef DECAL_AFTER_DETAIL #include #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) surfaceAlbedo*=vColor.rgb; #endif #ifdef DETAIL float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; #endif #ifdef DECAL_AFTER_DETAIL #include #endif #define CUSTOM_FRAGMENT_UPDATE_ALBEDO #ifdef OPACITY #ifdef OPACITYRGB alpha=getLuminance(opacityMap.rgb); #else alpha*=opacityMap.a; #endif alpha*=vOpacityInfos.y; #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=vColor.a; #endif #if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) #ifdef ALPHATEST #if DEBUGMODE != 88 if (alpha0 #ifdef METALLICWORKFLOW vec2 metallicRoughness; #ifdef REFLECTIVITY vec4 surfaceMetallicColorMap; #endif #ifndef FROSTBITE_REFLECTANCE vec3 metallicF0; #endif #else #ifdef REFLECTIVITY vec4 surfaceReflectivityColorMap; #endif #endif #endif }; #define pbr_inline reflectivityOutParams reflectivityBlock( in vec4 vReflectivityColor #ifdef METALLICWORKFLOW ,in vec3 surfaceAlbedo ,in vec4 metallicReflectanceFactors #endif #ifdef REFLECTIVITY ,in vec3 reflectivityInfos ,in vec4 surfaceMetallicOrReflectivityColorMap #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) ,in vec3 ambientOcclusionColorIn #endif #ifdef MICROSURFACEMAP ,in vec4 microSurfaceTexel #endif #ifdef DETAIL ,in vec4 detailColor ,in vec4 vDetailInfos #endif ) {reflectivityOutParams outParams;float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; #ifdef METALLICWORKFLOW vec2 metallicRoughness=surfaceReflectivityColor.rg; #ifdef REFLECTIVITY #if DEBUGMODE>0 outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; #endif #ifdef AOSTOREINMETALMAPRED vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); #endif #ifdef METALLNESSSTOREINMETALMAPBLUE metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; #else metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; #endif #ifdef ROUGHNESSSTOREINMETALMAPALPHA metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; #else #ifdef ROUGHNESSSTOREINMETALMAPGREEN metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; #endif #endif #endif #ifdef DETAIL float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); #endif #ifdef MICROSURFACEMAP metallicRoughness.g*=microSurfaceTexel.r; #endif #if DEBUGMODE>0 outParams.metallicRoughness=metallicRoughness; #endif #define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; #ifdef FROSTBITE_REFLECTANCE outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); #else vec3 metallicF0=metallicReflectanceFactors.rgb; #if DEBUGMODE>0 outParams.metallicF0=metallicF0; #endif outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); #endif #else #ifdef REFLECTIVITY surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; #if DEBUGMODE>0 outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; #endif #ifdef MICROSURFACEFROMREFLECTIVITYMAP microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; #else #ifdef MICROSURFACEAUTOMATIC microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); #endif #ifdef MICROSURFACEMAP microSurface*=microSurfaceTexel.r; #endif #define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE #endif #endif #endif microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;} `;de.IncludesShadersStore[m6t]=g6t;const _6t="pbrBlockAmbientOcclusion",v6t=`struct ambientOcclusionOutParams {vec3 ambientOcclusionColor; #if DEBUGMODE>0 && defined(AMBIENT) vec3 ambientOcclusionColorMap; #endif };ambientOcclusionOutParams ambientOcclusionBlock( #ifdef AMBIENT in vec3 ambientOcclusionColorMap_, in vec4 vAmbientInfos #endif ) {ambientOcclusionOutParams outParams;vec3 ambientOcclusionColor=vec3(1.,1.,1.); #ifdef AMBIENT vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; #ifdef AMBIENTINGRAYSCALE ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); #endif ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); #if DEBUGMODE>0 outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; #endif #endif outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;} `;de.IncludesShadersStore[_6t]=v6t;const y6t="pbrBlockAlphaFresnel",x6t=`#ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) struct alphaFresnelOutParams {float alpha;}; #define pbr_inline alphaFresnelOutParams alphaFresnelBlock( in vec3 normalW, in vec3 viewDirectionW, in float alpha, in float microSurface ) {alphaFresnelOutParams outParams;float opacityPerceptual=alpha; #ifdef LINEARALPHAFRESNEL float opacity0=opacityPerceptual; #else float opacity0=opacityPerceptual*opacityPerceptual; #endif float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; #ifdef ALPHATEST if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) vec3 anisotropyMapData; #endif }; #define pbr_inline anisotropicOutParams anisotropicBlock( in vec3 vAnisotropy, in float roughness, #ifdef ANISOTROPIC_TEXTURE in vec3 anisotropyMapData, #endif in mat3 TBN, in vec3 normalW, in vec3 viewDirectionW ) {anisotropicOutParams outParams;float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); #ifdef ANISOTROPIC_TEXTURE anisotropy*=anisotropyMapData.b; #if DEBUGMODE>0 outParams.anisotropyMapData=anisotropyMapData; #endif anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; #ifdef ANISOTROPIC_LEGACY anisotropyDirection.rg*=anisotropyMapData.rg; #else anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); #endif #endif mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;} #endif `;de.IncludesShadersStore[A6t]=b6t;const C6t="pbrBlockReflection",S6t=`#ifdef REFLECTION struct reflectionOutParams {vec4 environmentRadiance;vec3 environmentIrradiance; #ifdef REFLECTIONMAP_3D vec3 reflectionCoords; #else vec2 reflectionCoords; #endif #ifdef SS_TRANSLUCENCY #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) vec3 irradianceVector; #endif #endif #endif }; #define pbr_inline void createReflectionCoords( in vec3 vPositionW, in vec3 normalW, #ifdef ANISOTROPIC in anisotropicOutParams anisotropicOut, #endif #ifdef REFLECTIONMAP_3D out vec3 reflectionCoords #else out vec2 reflectionCoords #endif ) { #ifdef ANISOTROPIC vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); #else vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #endif #ifdef REFLECTIONMAP_OPPOSITEZ reflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D reflectionCoords=reflectionVector; #else reflectionCoords=reflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION reflectionCoords/=reflectionVector.z; #endif reflectionCoords.y=1.0-reflectionCoords.y; #endif } #define pbr_inline #define inline void sampleReflectionTexture( in float alphaG, in vec3 vReflectionMicrosurfaceInfos, in vec2 vReflectionInfos, in vec3 vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) in float NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION in float roughness, #endif #ifdef REFLECTIONMAP_3D in samplerCube reflectionSampler, const vec3 reflectionCoords, #else in sampler2D reflectionSampler, const vec2 reflectionCoords, #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D in samplerCube reflectionSamplerLow, in samplerCube reflectionSamplerHigh, #else in sampler2D reflectionSamplerLow, in sampler2D reflectionSamplerHigh, #endif #endif #ifdef REALTIME_FILTERING in vec2 vReflectionFilteringInfo, #endif out vec4 environmentRadiance ) { #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); #elif defined(LINEARSPECULARREFLECTION) float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); #else float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); #endif #ifdef LODBASEDMICROSFURACE reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; #ifdef LODINREFLECTIONALPHA float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); #else float requestedReflectionLOD=reflectionLOD; #endif #ifdef REALTIME_FILTERING environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); #else environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); #endif #else float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( sampleReflection(reflectionSamplerHigh,reflectionCoords), environmentMid, lodReflectionNormalizedDoubled );} else {environmentRadiance=mix( environmentMid, sampleReflection(reflectionSamplerLow,reflectionCoords), lodReflectionNormalizedDoubled-1.0 );} #endif #ifdef RGBDREFLECTION environmentRadiance.rgb=fromRGBD(environmentRadiance); #endif #ifdef GAMMAREFLECTION environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); #endif environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} #define pbr_inline #define inline reflectionOutParams reflectionBlock( in vec3 vPositionW ,in vec3 normalW ,in float alphaG ,in vec3 vReflectionMicrosurfaceInfos ,in vec2 vReflectionInfos ,in vec3 vReflectionColor #ifdef ANISOTROPIC ,in anisotropicOutParams anisotropicOut #endif #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,in float NdotVUnclamped #endif #ifdef LINEARSPECULARREFLECTION ,in float roughness #endif #ifdef REFLECTIONMAP_3D ,in samplerCube reflectionSampler #else ,in sampler2D reflectionSampler #endif #if defined(NORMAL) && defined(USESPHERICALINVERTEX) ,in vec3 vEnvironmentIrradiance #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,in mat4 reflectionMatrix #endif #endif #ifdef USEIRRADIANCEMAP #ifdef REFLECTIONMAP_3D ,in samplerCube irradianceSampler #else ,in sampler2D irradianceSampler #endif #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,in samplerCube reflectionSamplerLow ,in samplerCube reflectionSamplerHigh #else ,in sampler2D reflectionSamplerLow ,in sampler2D reflectionSamplerHigh #endif #endif #ifdef REALTIME_FILTERING ,in vec2 vReflectionFilteringInfo #endif ) {reflectionOutParams outParams;vec4 environmentRadiance=vec4(0.,0.,0.,0.); #ifdef REFLECTIONMAP_3D vec3 reflectionCoords=vec3(0.); #else vec2 reflectionCoords=vec2(0.); #endif createReflectionCoords( vPositionW, normalW, #ifdef ANISOTROPIC anisotropicOut, #endif reflectionCoords );sampleReflectionTexture( alphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION roughness, #endif #ifdef REFLECTIONMAP_3D reflectionSampler, reflectionCoords, #else reflectionSampler, reflectionCoords, #endif #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif environmentRadiance );vec3 environmentIrradiance=vec3(0.,0.,0.); #ifdef USESPHERICALFROMREFLECTIONMAP #if defined(NORMAL) && defined(USESPHERICALINVERTEX) environmentIrradiance=vEnvironmentIrradiance; #else #ifdef ANISOTROPIC vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; #else vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; #endif #ifdef REFLECTIONMAP_OPPOSITEZ irradianceVector.z*=-1.0; #endif #ifdef INVERTCUBICMAP irradianceVector.y*=-1.0; #endif #if defined(REALTIME_FILTERING) environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); #else environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); #endif #ifdef SS_TRANSLUCENCY outParams.irradianceVector=irradianceVector; #endif #endif #elif defined(USEIRRADIANCEMAP) vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; #ifdef RGBDREFLECTION environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); #endif #ifdef GAMMAREFLECTION environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); #endif #endif environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;} #endif `;de.IncludesShadersStore[C6t]=S6t;const E6t="pbrBlockSheen",T6t=`#ifdef SHEEN struct sheenOutParams {float sheenIntensity;vec3 sheenColor;float sheenRoughness; #ifdef SHEEN_LINKWITHALBEDO vec3 surfaceAlbedo; #endif #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) float sheenAlbedoScaling; #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) vec3 finalSheenRadianceScaled; #endif #if DEBUGMODE>0 #ifdef SHEEN_TEXTURE vec4 sheenMapData; #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) vec3 sheenEnvironmentReflectance; #endif #endif }; #define pbr_inline #define inline sheenOutParams sheenBlock( in vec4 vSheenColor #ifdef SHEEN_ROUGHNESS ,in float vSheenRoughness #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) ,in vec4 sheenMapRoughnessData #endif #endif ,in float roughness #ifdef SHEEN_TEXTURE ,in vec4 sheenMapData ,in float sheenMapLevel #endif ,in float reflectance #ifdef SHEEN_LINKWITHALBEDO ,in vec3 baseColor ,in vec3 surfaceAlbedo #endif #ifdef ENVIRONMENTBRDF ,in float NdotV ,in vec3 environmentBrdf #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) ,in vec2 AARoughnessFactors ,in vec3 vReflectionMicrosurfaceInfos ,in vec2 vReflectionInfos ,in vec3 vReflectionColor ,in vec4 vLightingIntensity #ifdef REFLECTIONMAP_3D ,in samplerCube reflectionSampler ,in vec3 reflectionCoords #else ,in sampler2D reflectionSampler ,in vec2 reflectionCoords #endif ,in float NdotVUnclamped #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,in samplerCube reflectionSamplerLow ,in samplerCube reflectionSamplerHigh #else ,in sampler2D reflectionSamplerLow ,in sampler2D reflectionSamplerHigh #endif #endif #ifdef REALTIME_FILTERING ,in vec2 vReflectionFilteringInfo #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) ,in float seo #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) ,in float eho #endif #endif ) {sheenOutParams outParams;float sheenIntensity=vSheenColor.a; #ifdef SHEEN_TEXTURE #if DEBUGMODE>0 outParams.sheenMapData=sheenMapData; #endif #endif #ifdef SHEEN_LINKWITHALBEDO float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; #ifdef SHEEN_TEXTURE sheenIntensity*=sheenMapData.a; #endif #else vec3 sheenColor=vSheenColor.rgb; #ifdef SHEEN_TEXTURE #ifdef SHEEN_GAMMATEXTURE sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); #else sheenColor.rgb*=sheenMapData.rgb; #endif sheenColor.rgb*=sheenMapLevel; #endif #ifdef SHEEN_ROUGHNESS float sheenRoughness=vSheenRoughness; #ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE #if defined(SHEEN_TEXTURE) sheenRoughness*=sheenMapData.a; #endif #elif defined(SHEEN_TEXTURE_ROUGHNESS) sheenRoughness*=sheenMapRoughnessData.a; #endif #else float sheenRoughness=roughness; #ifdef SHEEN_TEXTURE sheenIntensity*=sheenMapData.a; #endif #endif #if !defined(SHEEN_ALBEDOSCALING) sheenIntensity*=(1.-reflectance); #endif sheenColor*=sheenIntensity; #endif #ifdef ENVIRONMENTBRDF /*#ifdef SHEEN_SOFTER vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); #else*/ #ifdef SHEEN_ROUGHNESS vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); #else vec3 environmentSheenBrdf=environmentBrdf; #endif /*#endif*/ #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); #ifdef SPECULARAA sheenAlphaG+=AARoughnessFactors.y; #endif vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( sheenAlphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) NdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION sheenRoughness, #endif reflectionSampler, reflectionCoords, #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif environmentSheenRadiance );vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) sheenEnvironmentReflectance*=seo; #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) sheenEnvironmentReflectance*=eho; #endif #if DEBUGMODE>0 outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; #endif outParams.finalSheenRadianceScaled= environmentSheenRadiance.rgb * sheenEnvironmentReflectance * vLightingIntensity.z; #endif #if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; #endif outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;} #endif `;de.IncludesShadersStore[E6t]=T6t;const M6t="pbrBlockClearcoat",R6t=`struct clearcoatOutParams {vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; #ifdef REFLECTION vec3 finalClearCoatRadianceScaled; #endif #ifdef CLEARCOAT_TINT vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; #endif #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) vec3 energyConservationFactorClearCoat; #endif #if DEBUGMODE>0 #ifdef CLEARCOAT_BUMP mat3 TBNClearCoat; #endif #ifdef CLEARCOAT_TEXTURE vec2 clearCoatMapData; #endif #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) vec4 clearCoatTintMapData; #endif #ifdef REFLECTION vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; #endif float clearCoatNdotV; #endif }; #ifdef CLEARCOAT #define pbr_inline #define inline clearcoatOutParams clearcoatBlock( in vec3 vPositionW ,in vec3 geometricNormalW ,in vec3 viewDirectionW ,in vec2 vClearCoatParams #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) ,in vec4 clearCoatMapRoughnessData #endif ,in vec3 specularEnvironmentR0 #ifdef CLEARCOAT_TEXTURE ,in vec2 clearCoatMapData #endif #ifdef CLEARCOAT_TINT ,in vec4 vClearCoatTintParams ,in float clearCoatColorAtDistance ,in vec4 vClearCoatRefractionParams #ifdef CLEARCOAT_TINT_TEXTURE ,in vec4 clearCoatTintMapData #endif #endif #ifdef CLEARCOAT_BUMP ,in vec2 vClearCoatBumpInfos ,in vec4 clearCoatBumpMapData ,in vec2 vClearCoatBumpUV #if defined(TANGENT) && defined(NORMAL) ,in mat3 vTBN #else ,in vec2 vClearCoatTangentSpaceParams #endif #ifdef OBJECTSPACE_NORMALMAP ,in mat4 normalMatrix #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) ,in vec3 faceNormal #endif #ifdef REFLECTION ,in vec3 vReflectionMicrosurfaceInfos ,in vec2 vReflectionInfos ,in vec3 vReflectionColor ,in vec4 vLightingIntensity #ifdef REFLECTIONMAP_3D ,in samplerCube reflectionSampler #else ,in sampler2D reflectionSampler #endif #ifndef LODBASEDMICROSFURACE #ifdef REFLECTIONMAP_3D ,in samplerCube reflectionSamplerLow ,in samplerCube reflectionSamplerHigh #else ,in sampler2D reflectionSamplerLow ,in sampler2D reflectionSamplerHigh #endif #endif #ifdef REALTIME_FILTERING ,in vec2 vReflectionFilteringInfo #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION ,in float ambientMonochrome #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) ,in float frontFacingMultiplier #endif ) {clearcoatOutParams outParams;float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; #ifdef CLEARCOAT_TEXTURE clearCoatIntensity*=clearCoatMapData.x; #ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE clearCoatRoughness*=clearCoatMapData.y; #endif #if DEBUGMODE>0 outParams.clearCoatMapData=clearCoatMapData; #endif #endif #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) clearCoatRoughness*=clearCoatMapRoughnessData.y; #endif outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; #ifdef CLEARCOAT_TINT vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; #ifdef CLEARCOAT_TINT_TEXTURE #ifdef CLEARCOAT_TINT_GAMMATEXTURE clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); #else clearCoatColor*=clearCoatTintMapData.rgb; #endif clearCoatThickness*=clearCoatTintMapData.a; #if DEBUGMODE>0 outParams.clearCoatTintMapData=clearCoatTintMapData; #endif #endif outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; #endif #ifdef CLEARCOAT_REMAP_F0 vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); #else vec3 specularEnvironmentR0Updated=specularEnvironmentR0; #endif outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; #ifdef CLEARCOAT_BUMP #ifdef NORMALXYSCALE float clearCoatNormalScale=1.0; #else float clearCoatNormalScale=vClearCoatBumpInfos.y; #endif #if defined(TANGENT) && defined(NORMAL) mat3 TBNClearCoat=vTBN; #else vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); #endif #if DEBUGMODE>0 outParams.TBNClearCoat=TBNClearCoat; #endif #ifdef OBJECTSPACE_NORMALMAP clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); #else clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); #endif #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; #endif outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); #if DEBUGMODE>0 outParams.clearCoatNdotV=clearCoatNdotV; #endif #ifdef CLEARCOAT_TINT vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); #endif #if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); #endif #if defined(REFLECTION) float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); #ifdef SPECULARAA clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; #endif vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); #ifdef REFLECTIONMAP_OPPOSITEZ clearCoatReflectionVector.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D vec3 clearCoatReflectionCoords=clearCoatReflectionVector; #else vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; #ifdef REFLECTIONMAP_PROJECTION clearCoatReflectionCoords/=clearCoatReflectionVector.z; #endif clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; #endif sampleReflectionTexture( clearCoatAlphaG, vReflectionMicrosurfaceInfos, vReflectionInfos, vReflectionColor, #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) clearCoatNdotVUnclamped, #endif #ifdef LINEARSPECULARREFLECTION clearCoatRoughness, #endif reflectionSampler, clearCoatReflectionCoords, #ifndef LODBASEDMICROSFURACE reflectionSamplerLow, reflectionSamplerHigh, #endif #ifdef REALTIME_FILTERING vReflectionFilteringInfo, #endif environmentClearCoatRadiance ); #if DEBUGMODE>0 outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; #endif #endif #endif #else vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); #endif clearCoatEnvironmentReflectance*=clearCoatIntensity; #if DEBUGMODE>0 outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; #endif outParams.finalClearCoatRadianceScaled= environmentClearCoatRadiance.rgb * clearCoatEnvironmentReflectance * vLightingIntensity.z; #endif #if defined(CLEARCOAT_TINT) outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); #endif float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); #endif return outParams;} #endif `;de.IncludesShadersStore[M6t]=R6t;const I6t="pbrBlockIridescence",P6t=`struct iridescenceOutParams {float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; #ifdef IRIDESCENCE #define pbr_inline #define inline iridescenceOutParams iridescenceBlock( in vec4 vIridescenceParams ,in float viewAngle ,in vec3 specularEnvironmentR0 #ifdef IRIDESCENCE_TEXTURE ,in vec2 iridescenceMapData #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE ,in vec2 iridescenceThicknessMapData #endif #ifdef CLEARCOAT ,in float NdotVUnclamped #ifdef CLEARCOAT_TEXTURE ,in vec2 clearCoatMapData #endif #endif ) {iridescenceOutParams outParams;float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; #ifdef IRIDESCENCE_TEXTURE iridescenceIntensity*=iridescenceMapData.x; #endif #if defined(IRIDESCENCE_THICKNESS_TEXTURE) iridescenceThicknessWeight=iridescenceThicknessMapData.g; #endif float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; #ifdef CLEARCOAT float clearCoatIntensity=vClearCoatParams.x; #ifdef CLEARCOAT_TEXTURE clearCoatIntensity*=clearCoatMapData.x; #endif topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); #endif vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;} #endif `;de.IncludesShadersStore[I6t]=P6t;const w6t="pbrBlockSubSurface",D6t=`struct subSurfaceOutParams {vec3 specularEnvironmentReflectance; #ifdef SS_REFRACTION vec3 finalRefraction;vec3 surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY float alpha; #endif #ifdef REFLECTION float refractionFactorForIrradiance; #endif #endif #ifdef SS_TRANSLUCENCY vec3 transmittance;float translucencyIntensity; #ifdef REFLECTION vec3 refractionIrradiance; #endif #endif #if DEBUGMODE>0 #ifdef SS_THICKNESSANDMASK_TEXTURE vec4 thicknessMap; #endif #ifdef SS_REFRACTION vec4 environmentRefraction;vec3 refractionTransmittance; #endif #endif }; #ifdef SUBSURFACE #ifdef SS_REFRACTION #define pbr_inline #define inline vec4 sampleEnvironmentRefraction( in float ior ,in float thickness ,in float refractionLOD ,in vec3 normalW ,in vec3 vPositionW ,in vec3 viewDirectionW ,in mat4 view ,in vec4 vRefractionInfos ,in mat4 refractionMatrix ,in vec4 vRefractionMicrosurfaceInfos ,in float alphaG #ifdef SS_REFRACTIONMAP_3D ,in samplerCube refractionSampler #ifndef LODBASEDMICROSFURACE ,in samplerCube refractionSamplerLow ,in samplerCube refractionSamplerHigh #endif #else ,in sampler2D refractionSampler #ifndef LODBASEDMICROSFURACE ,in sampler2D refractionSamplerLow ,in sampler2D refractionSamplerHigh #endif #endif #ifdef ANISOTROPIC ,in anisotropicOutParams anisotropicOut #endif #ifdef REALTIME_FILTERING ,in vec2 vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,in vec3 refractionPosition ,in vec3 refractionSize #endif ) {vec4 environmentRefraction=vec4(0.,0.,0.,0.); #ifdef ANISOTROPIC vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); #else vec3 refractionVector=refract(-viewDirectionW,normalW,ior); #endif #ifdef SS_REFRACTIONMAP_OPPOSITEZ refractionVector.z*=-1.0; #endif #ifdef SS_REFRACTIONMAP_3D #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); #endif refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); #else #ifdef SS_USE_THICKNESS_AS_DEPTH vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); #else vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); #endif vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; #endif #ifdef LODBASEDMICROSFURACE refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; #ifdef SS_LODINREFRACTIONALPHA float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); #else float requestedRefractionLOD=refractionLOD; #endif #if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); #else environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); #endif #else float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( sampleRefraction(refractionSamplerHigh,refractionCoords), environmentRefractionMid, lodRefractionNormalizedDoubled );} else {environmentRefraction=mix( environmentRefractionMid, sampleRefraction(refractionSamplerLow,refractionCoords), lodRefractionNormalizedDoubled-1.0 );} #endif #ifdef SS_RGBDREFRACTION environmentRefraction.rgb=fromRGBD(environmentRefraction); #endif #ifdef SS_GAMMAREFRACTION environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); #endif return environmentRefraction;} #endif #define pbr_inline #define inline subSurfaceOutParams subSurfaceBlock( in vec3 vSubSurfaceIntensity ,in vec2 vThicknessParam ,in vec4 vTintColor ,in vec3 normalW ,in vec3 specularEnvironmentReflectance #ifdef SS_THICKNESSANDMASK_TEXTURE ,in vec4 thicknessMap #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE ,in vec4 refractionIntensityMap #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE ,in vec4 translucencyIntensityMap #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY ,in mat4 reflectionMatrix #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,in vec3 irradianceVector_ #endif #if defined(REALTIME_FILTERING) ,in samplerCube reflectionSampler ,in vec2 vReflectionFilteringInfo #endif #endif #ifdef USEIRRADIANCEMAP #ifdef REFLECTIONMAP_3D ,in samplerCube irradianceSampler #else ,in sampler2D irradianceSampler #endif #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) ,in vec3 surfaceAlbedo #endif #ifdef SS_REFRACTION ,in vec3 vPositionW ,in vec3 viewDirectionW ,in mat4 view ,in vec4 vRefractionInfos ,in mat4 refractionMatrix ,in vec4 vRefractionMicrosurfaceInfos ,in vec4 vLightingIntensity #ifdef SS_LINKREFRACTIONTOTRANSPARENCY ,in float alpha #endif #ifdef SS_LODINREFRACTIONALPHA ,in float NdotVUnclamped #endif #ifdef SS_LINEARSPECULARREFRACTION ,in float roughness #endif ,in float alphaG #ifdef SS_REFRACTIONMAP_3D ,in samplerCube refractionSampler #ifndef LODBASEDMICROSFURACE ,in samplerCube refractionSamplerLow ,in samplerCube refractionSamplerHigh #endif #else ,in sampler2D refractionSampler #ifndef LODBASEDMICROSFURACE ,in sampler2D refractionSamplerLow ,in sampler2D refractionSamplerHigh #endif #endif #ifdef ANISOTROPIC ,in anisotropicOutParams anisotropicOut #endif #ifdef REALTIME_FILTERING ,in vec2 vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,in vec3 refractionPosition ,in vec3 refractionSize #endif #ifdef SS_DISPERSION ,in float dispersion #endif #endif #ifdef SS_TRANSLUCENCY ,in vec3 vDiffusionDistance ,in vec4 vTranslucencyColor #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE ,in vec4 translucencyColorMap #endif #endif ) {subSurfaceOutParams outParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; #ifdef SS_REFRACTION float refractionIntensity=vSubSurfaceIntensity.x; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; #endif #endif #ifdef SS_TRANSLUCENCY float translucencyIntensity=vSubSurfaceIntensity.y; #endif #ifdef SS_THICKNESSANDMASK_TEXTURE #ifdef SS_USE_GLTF_TEXTURES float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; #else float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; #endif #if DEBUGMODE>0 outParams.thicknessMap=thicknessMap; #endif #if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS) #ifdef SS_USE_GLTF_TEXTURES refractionIntensity*=thicknessMap.r; #else refractionIntensity*=thicknessMap.g; #endif #endif #if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS) #ifdef SS_USE_GLTF_TEXTURES translucencyIntensity*=thicknessMap.a; #else translucencyIntensity*=thicknessMap.b; #endif #endif #else float thickness=vThicknessParam.y; #endif #if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE) #ifdef SS_USE_GLTF_TEXTURES refractionIntensity*=refractionIntensityMap.r; #else refractionIntensity*=refractionIntensityMap.g; #endif #endif #if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE) #ifdef SS_USE_GLTF_TEXTURES translucencyIntensity*=translucencyIntensityMap.a; #else translucencyIntensity*=translucencyIntensityMap.b; #endif #endif #ifdef SS_TRANSLUCENCY thickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor; #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE translucencyColor*=translucencyColorMap; #endif vec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; #endif #ifdef SS_REFRACTION vec4 environmentRefraction=vec4(0.,0.,0.,0.); #ifdef SS_HAS_THICKNESS float ior=vRefractionInfos.y; #else float ior=vRefractionMicrosurfaceInfos.w; #endif #ifdef SS_LODINREFRACTIONALPHA float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); #elif defined(SS_LINEARSPECULARREFRACTION) float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); #else float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); #endif float refraction_ior=vRefractionInfos.y; #ifdef SS_DISPERSION float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i]; #endif vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG #ifdef SS_REFRACTIONMAP_3D ,refractionSampler #ifndef LODBASEDMICROSFURACE ,refractionSamplerLow ,refractionSamplerHigh #endif #else ,refractionSampler #ifndef LODBASEDMICROSFURACE ,refractionSamplerLow ,refractionSamplerHigh #endif #endif #ifdef ANISOTROPIC ,anisotropicOut #endif #ifdef REALTIME_FILTERING ,vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,refractionPosition ,refractionSize #endif ); #ifdef SS_DISPERSION environmentRefraction[i]=envSample[i];} #else environmentRefraction=envSample; #endif environmentRefraction.rgb*=vRefractionInfos.x; #endif #ifdef SS_REFRACTION vec3 refractionTransmittance=vec3(refractionIntensity); #ifdef SS_THICKNESSANDMASK_TEXTURE vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); #elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; #else vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); #endif #ifdef SS_ALBEDOFORREFRACTIONTINT environmentRefraction.rgb*=surfaceAlbedo.rgb; #endif outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); #ifdef REFLECTION outParams.refractionFactorForIrradiance=(1.-refractionIntensity); #endif #ifdef UNUSED_MULTIPLEBOUNCES vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); #endif refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; #if DEBUGMODE>0 outParams.refractionTransmittance=refractionTransmittance; #endif outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; #if DEBUGMODE>0 outParams.environmentRefraction=environmentRefraction; #endif #endif #if defined(REFLECTION) && defined(SS_TRANSLUCENCY) #if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; #ifdef REFLECTIONMAP_OPPOSITEZ irradianceVector.z*=-1.0; #endif #ifdef INVERTCUBICMAP irradianceVector.y*=-1.0; #endif #else vec3 irradianceVector=irradianceVector_; #endif #if defined(USESPHERICALFROMREFLECTIONMAP) #if defined(REALTIME_FILTERING) vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); #else vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); #endif #elif defined(USEIRRADIANCEMAP) #ifdef REFLECTIONMAP_3D vec3 irradianceCoords=irradianceVector; #else vec2 irradianceCoords=irradianceVector.xy; #ifdef REFLECTIONMAP_PROJECTION irradianceCoords/=irradianceVector.z; #endif irradianceCoords.y=1.0-irradianceCoords.y; #endif vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); #ifdef RGBDREFLECTION refractionIrradiance.rgb=fromRGBD(refractionIrradiance); #endif #ifdef GAMMAREFLECTION refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); #endif #else vec4 refractionIrradiance=vec4(0.); #endif refractionIrradiance.rgb*=transmittance; #ifdef SS_ALBEDOFORTRANSLUCENCYTINT refractionIrradiance.rgb*=surfaceAlbedo.rgb; #endif outParams.refractionIrradiance=refractionIrradiance.rgb; #endif return outParams;} #endif `;de.IncludesShadersStore[w6t]=D6t;const L6t="pbrBlockNormalGeometric",O6t=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #endif vec3 geometricNormalW=normalW; #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; #endif `;de.IncludesShadersStore[L6t]=O6t;const cKe="bumpFragment",uKe=`vec2 uvOffset=vec2(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE float normalScale=1.0; #elif defined(BUMP) float normalScale=vBumpInfos.y; #else float normalScale=1.0; #endif #if defined(TANGENT) && defined(NORMAL) mat3 TBN=vTBN; #elif defined(BUMP) vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); #else vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); #endif #elif defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) mat3 TBN=vTBN; #else vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); #endif #endif #ifdef PARALLAX mat3 invTBN=transposeMat3(TBN); #ifdef PARALLAXOCCLUSION uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); #else uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); #endif #endif #ifdef DETAIL vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); #endif #ifdef BUMP #ifdef OBJECTSPACE_NORMALMAP #define CUSTOM_FRAGMENT_BUMP_FRAGMENT normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); #elif !defined(DETAIL) normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); #else vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; #if DETAIL_NORMALBLENDMETHOD==0 detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); #elif DETAIL_NORMALBLENDMETHOD==1 detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; #endif normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); #endif #elif defined(DETAIL) detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); #endif `;de.IncludesShadersStore[cKe]=uKe;const hKe={name:cKe,shader:uKe},N6t=Object.freeze(Object.defineProperty({__proto__:null,bumpFragment:hKe},Symbol.toStringTag,{value:"Module"})),F6t="pbrBlockNormalFinal",B6t=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; #endif normalW*=sign(dot(normalW,faceNormal)); #endif #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) normalW=gl_FrontFacing ? normalW : -normalW; #endif `;de.IncludesShadersStore[F6t]=B6t;const k6t="depthPrePass",U6t=`#ifdef DEPTHPREPASS gl_FragColor=vec4(0.,0.,0.,1.0);return; #endif `;de.IncludesShadersStore[k6t]=U6t;const z6t="pbrBlockLightmapInit",V6t=`#ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); #endif #ifdef GAMMALIGHTMAP lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif `;de.IncludesShadersStore[z6t]=V6t;const G6t="pbrBlockGeometryInfo",W6t=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); #ifdef SPECULARAA alphaG+=AARoughnessFactors.y; #endif #if defined(ENVIRONMENTBRDF) vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION #ifdef AMBIENTINGRAYSCALE float ambientMonochrome=aoOut.ambientOcclusionColor.r; #else float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); #endif float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); #endif #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); #endif #endif #endif #endif `;de.IncludesShadersStore[G6t]=W6t;const K6t="pbrBlockReflectance0",H6t=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; #ifdef METALLICWORKFLOW vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); #else vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); #endif #ifdef ALPHAFRESNEL float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; #endif `;de.IncludesShadersStore[K6t]=H6t;const j6t="pbrBlockReflectance",X6t=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); #ifdef RADIANCEOCCLUSION specularEnvironmentReflectance*=seo; #endif #ifdef HORIZONOCCLUSION #ifdef BUMP #ifdef REFLECTIONMAP_3D specularEnvironmentReflectance*=eho; #endif #endif #endif #else vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); #endif #ifdef CLEARCOAT specularEnvironmentReflectance*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) specularEnvironmentReflectance*=clearcoatOut.absorption; #endif #endif `;de.IncludesShadersStore[j6t]=X6t;const Y6t="pbrBlockDirectLighting",Q6t=`vec3 diffuseBase=vec3(0.,0.,0.); #ifdef SPECULARTERM vec3 specularBase=vec3(0.,0.,0.); #endif #ifdef CLEARCOAT vec3 clearCoatBase=vec3(0.,0.,0.); #endif #ifdef SHEEN vec3 sheenBase=vec3(0.,0.,0.); #endif preLightingInfo preInfo;lightingInfo info;float shadow=1.; float aggShadow=0.;float numLights=0.; #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) vec3 absorption=vec3(0.); #endif `;de.IncludesShadersStore[Y6t]=Q6t;const $6t="pbrBlockFinalLitComponents",Z6t=`aggShadow=aggShadow/numLights; #if defined(ENVIRONMENTBRDF) #ifdef MS_BRDF_ENERGY_CONSERVATION vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); #endif #endif #ifndef METALLICWORKFLOW #ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; #endif #endif #if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; #endif #ifdef REFLECTION vec3 finalIrradiance=reflectionOut.environmentIrradiance; #if defined(CLEARCOAT) finalIrradiance*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) finalIrradiance*=clearcoatOut.absorption; #endif #endif #if defined(SS_REFRACTION) finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; #endif #if defined(SS_TRANSLUCENCY) finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; #endif finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; #endif #ifdef SPECULARTERM vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalSpecularScaled*=energyConservationFactor; #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) finalSpecularScaled*=sheenOut.sheenAlbedoScaling; #endif #endif #ifdef REFLECTION vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalRadianceScaled*=energyConservationFactor; #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) finalRadianceScaled*=sheenOut.sheenAlbedoScaling; #endif #endif #ifdef SHEEN vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; #if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; #if defined(CLEARCOAT_TINT) sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; #endif #endif #endif #ifdef CLEARCOAT vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; #if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; #endif #ifdef SS_REFRACTION subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; #ifdef CLEARCOAT_TINT subSurfaceOut.finalRefraction*=clearcoatOut.absorption; #endif #endif #endif #ifdef ALPHABLEND float luminanceOverAlpha=0.0; #if defined(REFLECTION) && defined(RADIANCEOVERALPHA) luminanceOverAlpha+=getLuminance(finalRadianceScaled); #if defined(CLEARCOAT) luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); #endif #endif #if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) luminanceOverAlpha+=getLuminance(finalSpecularScaled); #endif #if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) luminanceOverAlpha+=getLuminance(finalClearCoatScaled); #endif #if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); #endif #endif `;de.IncludesShadersStore[$6t]=Z6t;const q6t="pbrBlockFinalUnlitComponents",J6t=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; #ifdef EMISSIVE vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; #ifdef GAMMAEMISSIVE finalEmissive*=toLinearSpace(emissiveColorTex.rgb); #else finalEmissive*=emissiveColorTex.rgb; #endif finalEmissive*= vEmissiveInfos.y; #endif finalEmissive*=vLightingIntensity.y; #ifdef AMBIENT vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); #else vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; #endif finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; `;de.IncludesShadersStore[q6t]=J6t;const eEt="pbrBlockFinalColorComposition",tEt=`vec4 finalColor=vec4( #ifndef UNLIT #ifdef REFLECTION finalIrradiance + #endif #ifdef SPECULARTERM finalSpecularScaled + #endif #ifdef SHEEN finalSheenScaled + #endif #ifdef CLEARCOAT finalClearCoatScaled + #endif #ifdef REFLECTION finalRadianceScaled + #if defined(SHEEN) && defined(ENVIRONMENTBRDF) sheenOut.finalSheenRadianceScaled + #endif #ifdef CLEARCOAT clearcoatOut.finalClearCoatRadianceScaled + #endif #endif #ifdef SS_REFRACTION subSurfaceOut.finalRefraction + #endif #endif finalAmbient + finalDiffuse, alpha); #ifdef LIGHTMAP #ifndef LIGHTMAPEXCLUDED #ifdef USELIGHTMAPASSHADOWMAP finalColor.rgb*=lightmapColor.rgb; #else finalColor.rgb+=lightmapColor.rgb; #endif #endif #endif finalColor.rgb+=finalEmissive; #define CUSTOM_FRAGMENT_BEFORE_FOG finalColor=max(finalColor,0.0); `;de.IncludesShadersStore[eEt]=tEt;const iEt="pbrBlockImageProcessing",rEt=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) #if !defined(SKIPFINALCOLORCLAMP) finalColor.rgb=clamp(finalColor.rgb,0.,30.0); #endif #else finalColor=applyImageProcessing(finalColor); #endif finalColor.a*=visibility; #ifdef PREMULTIPLYALPHA finalColor.rgb*=finalColor.a; #endif `;de.IncludesShadersStore[iEt]=rEt;const sEt="oitFragment",nEt=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY float fragDepth=gl_FragCoord.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; #endif ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); #ifdef USE_REVERSE_DEPTHBUFFER float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; #else float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; #endif float alphaMultiplier=1.0-lastFrontColor.a; #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepth>nearestDepth || fragDepthfurthestDepth) { #endif return;} #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepthfurthestDepth) { #else if (fragDepth>nearestDepth && fragDepth0 if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { #if DEBUGMODE==1 gl_FragColor.rgb=vPositionW.rgb; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==2 && defined(NORMAL) gl_FragColor.rgb=vNormalW.rgb; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) gl_FragColor.rgb=TBN[0]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) gl_FragColor.rgb=TBN[1]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==5 gl_FragColor.rgb=normalW; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==6 && defined(MAINUV1) gl_FragColor.rgb=vec3(vMainUV1,0.0); #elif DEBUGMODE==7 && defined(MAINUV2) gl_FragColor.rgb=vec3(vMainUV2,0.0); #elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==10 && defined(CLEARCOAT) gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==11 && defined(ANISOTROPIC) gl_FragColor.rgb=anisotropicOut.anisotropicNormal; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==12 && defined(ANISOTROPIC) gl_FragColor.rgb=anisotropicOut.anisotropicTangent; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==13 && defined(ANISOTROPIC) gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; #define DEBUGMODE_NORMALIZE #elif DEBUGMODE==20 && defined(ALBEDO) gl_FragColor.rgb=albedoTexture.rgb; #ifndef GAMMAALBEDO #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==21 && defined(AMBIENT) gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; #elif DEBUGMODE==22 && defined(OPACITY) gl_FragColor.rgb=opacityMap.rgb; #elif DEBUGMODE==23 && defined(EMISSIVE) gl_FragColor.rgb=emissiveColorTex.rgb; #ifndef GAMMAEMISSIVE #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==24 && defined(LIGHTMAP) gl_FragColor.rgb=lightmapColor.rgb; #ifndef GAMMALIGHTMAP #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; #elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); #elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; #elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) gl_FragColor.rgb=sheenOut.sheenMapData.rgb; #elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; #elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; #elif DEBUGMODE==32 && defined(BUMP) gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; #elif DEBUGMODE==40 && defined(SS_REFRACTION) gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==41 && defined(REFLECTION) gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; #ifndef GAMMAREFLECTION #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==50 gl_FragColor.rgb=diffuseBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==51 && defined(SPECULARTERM) gl_FragColor.rgb=specularBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==52 && defined(CLEARCOAT) gl_FragColor.rgb=clearCoatBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==53 && defined(SHEEN) gl_FragColor.rgb=sheenBase.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==54 && defined(REFLECTION) gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; #ifndef GAMMAREFLECTION #define DEBUGMODE_GAMMA #endif #elif DEBUGMODE==60 gl_FragColor.rgb=surfaceAlbedo.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==61 gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; #define DEBUGMODE_GAMMA #elif DEBUGMODE==62 && defined(METALLICWORKFLOW) gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); #elif DEBUGMODE==71 && defined(METALLICWORKFLOW) gl_FragColor.rgb=reflectivityOut.metallicF0; #elif DEBUGMODE==63 gl_FragColor.rgb=vec3(roughness); #elif DEBUGMODE==64 gl_FragColor.rgb=vec3(alphaG); #elif DEBUGMODE==65 gl_FragColor.rgb=vec3(NdotV); #elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==67 && defined(CLEARCOAT) gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); #elif DEBUGMODE==68 && defined(CLEARCOAT) gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); #elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) gl_FragColor.rgb=subSurfaceOut.transmittance; #elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; #elif DEBUGMODE==72 gl_FragColor.rgb=vec3(microSurface); #elif DEBUGMODE==73 gl_FragColor.rgb=vAlbedoColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) gl_FragColor.rgb=vReflectivityColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==75 gl_FragColor.rgb=vEmissiveColor.rgb; #define DEBUGMODE_GAMMA #elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) gl_FragColor.rgb=vec3(seo); #elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) gl_FragColor.rgb=vec3(eho); #elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) gl_FragColor.rgb=vec3(energyConservationFactor); #elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) gl_FragColor.rgb=specularEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; #define DEBUGMODE_GAMMA #elif DEBUGMODE==86 && defined(ALPHABLEND) gl_FragColor.rgb=vec3(luminanceOverAlpha); #elif DEBUGMODE==87 gl_FragColor.rgb=vec3(alpha); #elif DEBUGMODE==88 && defined(ALBEDO) gl_FragColor.rgb=vec3(albedoTexture.a); #elif DEBUGMODE==89 gl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb; #else float stripeWidth=30.;float stripePos=floor(gl_FragCoord.x/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); #endif gl_FragColor.rgb*=vDebugMode.y; #ifdef DEBUGMODE_NORMALIZE gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; #endif #ifdef DEBUGMODE_GAMMA gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); #endif gl_FragColor.a=1.0; #ifdef PREPASS gl_FragData[0]=toLinearSpace(gl_FragColor); gl_FragData[1]=vec4(0.,0.,0.,0.); #endif #ifdef DEBUGMODE_FORCERETURN return; #endif } #endif `;de.IncludesShadersStore[aEt]=oEt;const dKe="pbrPixelShader",fKe=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #extension GL_OES_standard_derivatives : enable #endif #ifdef LODBASEDMICROSFURACE #extension GL_EXT_shader_texture_lod : enable #endif #define CUSTOM_FRAGMENT_BEGIN #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include[SCENE_MRT_COUNT] precision highp float; #include #ifndef FROMLINEARSPACE #define FROMLINEARSPACE #endif #include<__decl__pbrFragment> #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef REFLECTION #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS #include #include #include #include #include #include #include #include #include #include void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #include #include #include albedoOpacityOutParams albedoOpacityOut; #ifdef ALBEDO vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); #endif #ifdef DECAL vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); #endif albedoOpacityOut=albedoOpacityBlock( vAlbedoColor #ifdef ALBEDO ,albedoTexture ,vAlbedoInfos #endif #ifdef OPACITY ,opacityMap ,vOpacityInfos #endif #ifdef DETAIL ,detailColor ,vDetailInfos #endif #ifdef DECAL ,decalColor ,vDecalInfos #endif );vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; #define CUSTOM_FRAGMENT_UPDATE_ALPHA #include #define CUSTOM_FRAGMENT_BEFORE_LIGHTS ambientOcclusionOutParams aoOut; #ifdef AMBIENT vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; #endif aoOut=ambientOcclusionBlock( #ifdef AMBIENT ambientOcclusionColorMap, vAmbientInfos #endif ); #include #ifdef UNLIT vec3 diffuseBase=vec3(1.,1.,1.); #else vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; #if defined(REFLECTIVITY) vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; #ifndef METALLICWORKFLOW #ifdef REFLECTIVITY_GAMMA surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); #endif surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; #endif #endif #if defined(MICROSURFACEMAP) vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; #endif #ifdef METALLICWORKFLOW vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; #ifdef REFLECTANCE vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); #ifdef REFLECTANCE_GAMMA reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); #endif metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; #endif #ifdef METALLIC_REFLECTANCE vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); #ifdef METALLIC_REFLECTANCE_GAMMA metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); #endif #ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; #endif metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; #endif #endif reflectivityOut=reflectivityBlock( vReflectivityColor #ifdef METALLICWORKFLOW ,surfaceAlbedo ,metallicReflectanceFactors #endif #ifdef REFLECTIVITY ,vReflectivityInfos ,surfaceMetallicOrReflectivityColorMap #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) ,aoOut.ambientOcclusionColor #endif #ifdef MICROSURFACEMAP ,microSurfaceTexel #endif #ifdef DETAIL ,detailColor ,vDetailInfos #endif );float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; #ifdef METALLICWORKFLOW surfaceAlbedo=reflectivityOut.surfaceAlbedo; #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; #endif #ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) alphaFresnelOutParams alphaFresnelOut;alphaFresnelOut=alphaFresnelBlock( normalW, viewDirectionW, alpha, microSurface );alpha=alphaFresnelOut.alpha; #endif #endif #include #ifdef ANISOTROPIC anisotropicOutParams anisotropicOut; #ifdef ANISOTROPIC_TEXTURE vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; #endif anisotropicOut=anisotropicBlock( vAnisotropy, roughness, #ifdef ANISOTROPIC_TEXTURE anisotropyMapData, #endif TBN, normalW, viewDirectionW ); #endif #ifdef REFLECTION reflectionOutParams reflectionOut; #ifndef USE_CUSTOM_REFLECTION reflectionOut=reflectionBlock( vPositionW ,normalW ,alphaG ,vReflectionMicrosurfaceInfos ,vReflectionInfos ,vReflectionColor #ifdef ANISOTROPIC ,anisotropicOut #endif #if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) ,NdotVUnclamped #endif #ifdef LINEARSPECULARREFLECTION ,roughness #endif ,reflectionSampler #if defined(NORMAL) && defined(USESPHERICALINVERTEX) ,vEnvironmentIrradiance #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,reflectionMatrix #endif #endif #ifdef USEIRRADIANCEMAP ,irradianceSampler #endif #ifndef LODBASEDMICROSFURACE ,reflectionSamplerLow ,reflectionSamplerHigh #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif ); #else #define CUSTOM_REFLECTION #endif #endif #include #ifdef SHEEN sheenOutParams sheenOut; #ifdef SHEEN_TEXTURE vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); #endif #if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; #endif sheenOut=sheenBlock( vSheenColor #ifdef SHEEN_ROUGHNESS ,vSheenRoughness #if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) ,sheenMapRoughnessData #endif #endif ,roughness #ifdef SHEEN_TEXTURE ,sheenMapData ,vSheenInfos.y #endif ,reflectance #ifdef SHEEN_LINKWITHALBEDO ,baseColor ,surfaceAlbedo #endif #ifdef ENVIRONMENTBRDF ,NdotV ,environmentBrdf #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) ,AARoughnessFactors ,vReflectionMicrosurfaceInfos ,vReflectionInfos ,vReflectionColor ,vLightingIntensity ,reflectionSampler ,reflectionOut.reflectionCoords ,NdotVUnclamped #ifndef LODBASEDMICROSFURACE ,reflectionSamplerLow ,reflectionSamplerHigh #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) ,seo #endif #if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) ,eho #endif #endif ); #ifdef SHEEN_LINKWITHALBEDO surfaceAlbedo=sheenOut.surfaceAlbedo; #endif #endif #ifdef CLEARCOAT #ifdef CLEARCOAT_TEXTURE vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; #endif #endif #ifdef IRIDESCENCE iridescenceOutParams iridescenceOut; #ifdef IRIDESCENCE_TEXTURE vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; #endif iridescenceOut=iridescenceBlock( vIridescenceParams ,NdotV ,specularEnvironmentR0 #ifdef IRIDESCENCE_TEXTURE ,iridescenceMapData #endif #ifdef IRIDESCENCE_THICKNESS_TEXTURE ,iridescenceThicknessMapData #endif #ifdef CLEARCOAT ,NdotVUnclamped #ifdef CLEARCOAT_TEXTURE ,clearCoatMapData #endif #endif );float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; #endif clearcoatOutParams clearcoatOut; #ifdef CLEARCOAT #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; #endif #if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); #endif #ifdef CLEARCOAT_BUMP vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); #endif clearcoatOut=clearcoatBlock( vPositionW ,geometricNormalW ,viewDirectionW ,vClearCoatParams #if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) ,clearCoatMapRoughnessData #endif ,specularEnvironmentR0 #ifdef CLEARCOAT_TEXTURE ,clearCoatMapData #endif #ifdef CLEARCOAT_TINT ,vClearCoatTintParams ,clearCoatColorAtDistance ,vClearCoatRefractionParams #ifdef CLEARCOAT_TINT_TEXTURE ,clearCoatTintMapData #endif #endif #ifdef CLEARCOAT_BUMP ,vClearCoatBumpInfos ,clearCoatBumpMapData ,vClearCoatBumpUV #if defined(TANGENT) && defined(NORMAL) ,vTBN #else ,vClearCoatTangentSpaceParams #endif #ifdef OBJECTSPACE_NORMALMAP ,normalMatrix #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) ,faceNormal #endif #ifdef REFLECTION ,vReflectionMicrosurfaceInfos ,vReflectionInfos ,vReflectionColor ,vLightingIntensity ,reflectionSampler #ifndef LODBASEDMICROSFURACE ,reflectionSamplerLow ,reflectionSamplerHigh #endif #ifdef REALTIME_FILTERING ,vReflectionFilteringInfo #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) #ifdef RADIANCEOCCLUSION ,ambientMonochrome #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) ,(gl_FrontFacing ? 1. : -1.) #endif ); #else clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; #endif #include subSurfaceOutParams subSurfaceOut; #ifdef SUBSURFACE #ifdef SS_THICKNESSANDMASK_TEXTURE vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); #endif #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE vec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset); #endif subSurfaceOut=subSurfaceBlock( vSubSurfaceIntensity ,vThicknessParam ,vTintColor ,normalW ,specularEnvironmentReflectance #ifdef SS_THICKNESSANDMASK_TEXTURE ,thicknessMap #endif #ifdef SS_REFRACTIONINTENSITY_TEXTURE ,refractionIntensityMap #endif #ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE ,translucencyIntensityMap #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY ,reflectionMatrix #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) ,reflectionOut.irradianceVector #endif #if defined(REALTIME_FILTERING) ,reflectionSampler ,vReflectionFilteringInfo #endif #endif #ifdef USEIRRADIANCEMAP ,irradianceSampler #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) ,surfaceAlbedo #endif #ifdef SS_REFRACTION ,vPositionW ,viewDirectionW ,view ,vRefractionInfos ,refractionMatrix ,vRefractionMicrosurfaceInfos ,vLightingIntensity #ifdef SS_LINKREFRACTIONTOTRANSPARENCY ,alpha #endif #ifdef SS_LODINREFRACTIONALPHA ,NdotVUnclamped #endif #ifdef SS_LINEARSPECULARREFRACTION ,roughness #endif ,alphaG ,refractionSampler #ifndef LODBASEDMICROSFURACE ,refractionSamplerLow ,refractionSamplerHigh #endif #ifdef ANISOTROPIC ,anisotropicOut #endif #ifdef REALTIME_FILTERING ,vRefractionFilteringInfo #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC ,vRefractionPosition ,vRefractionSize #endif #ifdef SS_DISPERSION ,dispersion #endif #endif #ifdef SS_TRANSLUCENCY ,vDiffusionDistance ,vTranslucencyColor #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE ,translucencyColorMap #endif #endif ); #ifdef SS_REFRACTION surfaceAlbedo=subSurfaceOut.surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha=subSurfaceOut.alpha; #endif #endif #else subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; #endif #include #include[0..maxSimultaneousLights] #include #endif #include #define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION #include #include #include(color,finalColor) #include #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO_SQRT vec3 sqAlbedo=sqrt(surfaceAlbedo); #endif #ifdef PREPASS_IRRADIANCE vec3 irradiance=finalDiffuse; #ifndef UNLIT #ifdef REFLECTION irradiance+=finalIrradiance; #endif #endif #ifdef SS_SCATTERING gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); irradiance/=sqAlbedo; #else gl_FragData[0]=finalColor; float scatteringDiffusionProfile=255.; #endif gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); #else gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); #endif #ifdef PREPASS_DEPTH gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); #else gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_ALBEDO_SQRT gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #ifndef UNLIT gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; #endif #endif #endif #if !defined(PREPASS) || defined(WEBGL2) gl_FragColor=finalColor; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} #endif #include #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStore[dKe]=fKe;const pKe={name:dKe,shader:fKe},mKe=Object.freeze(Object.defineProperty({__proto__:null,pbrPixelShader:pKe},Symbol.toStringTag,{value:"Module"}));var Qhe;(function(s){s[s.GLSL=0]="GLSL",s[s.WGSL=1]="WGSL"})(Qhe||(Qhe={}));class sx extends $r{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=he.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const r=this.getScene();r?r.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture():this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;e._features.support3DTextures?t=e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t=e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=n=>{if(typeof n!="string")return;let a=null,o=null,l;const c=n.split(` `);let u=0,h=0,d=0,f=0,p=0;for(let m=0;m0&&(m+1)%4===0)a[m]=255;else{const g=o[m];a[m]=g/p*255}t.is3D?(t.updateSize(u,u,u),e.updateRawTexture3D(t,a,5,!1)):(t.updateSize(u*u,u),e.updateRawTexture(t,a,5,!1)),t.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new sx(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new sx(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}sx._NoneEmptyLineRegex=/\S+/;ve("BABYLON.ColorGradingTexture",sx);class ow extends $r{constructor(e,t,i,r=!1,n=!0,a=null,o=null,l=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=xe.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=l,this._noMipmap=r,this.gammaSpace=n,this._onLoad=a,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?a&&(this._texture.isReady?Me.SetImmediate(()=>a()):this._texture.onLoadedObservable.add(a)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;const n=document.createElement("canvas");Xw(this.url,a=>{this._width=a.width,this._height=a.height,n.width=this._width,n.height=this._height;const o=n.getContext("2d");o.drawImage(a,0,0);const l=o.getImageData(0,0,a.width,a.height);this._buffer=l.data.buffer,n.remove(),e()},(a,o)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,o)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const n=this._getFloat32ArrayFromArrayBuffer(this._buffer),a=r3.ConvertPanoramaToCubemap(n,this._width,this._height,this._size,this._supersample),o=[];for(let l=0;l<6;l++){const c=a[ow._FacesMapping[l]];o.push(c)}return o};if(!e)return;const i=t(),r=this._texture;e.getEngine().updateRawCubeTexture(r,i,r.format,r.type,r.invertY),r.isReady=!0,e.removePendingData(r),r.onLoadedObservable.notifyObservers(r),r.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(e.byteLength*3/4);let r=0;for(let n=0;ne.length){fe.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let r=!1,n=!1,a=!1;switch(i.image_type){case hEt:r=!0;case lEt:n=!0;break;case dEt:r=!0;case cEt:break;case fEt:r=!0;case uEt:a=!0;break}let o;const l=i.pixel_size>>3,c=i.width*i.height*l;let u;if(n&&(u=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),r){o=new Uint8Array(c);let x,A,b,C=0;const T=new Uint8Array(l);for(;t>mEt){default:case vEt:h=0,f=1,g=i.width,d=0,p=1,m=i.height;break;case gEt:h=0,f=1,g=i.width,d=i.height-1,p=-1,m=-1;break;case yEt:h=i.width-1,f=-1,g=-1,d=0,p=1,m=i.height;break;case _Et:h=i.width-1,f=-1,g=-1,d=i.height-1,p=-1,m=-1;break}const _="_getImageData"+(a?"Grey":"")+i.pixel_size+"bits",y=gKe[_](i,u,o,d,p,m,h,f,g);s.getEngine()._uploadDataToTextureDirectly(s,y)}function xEt(s,e,t,i,r,n,a,o,l){const c=t,u=e,h=s.width,d=s.height;let f,p=0,m,g;const _=new Uint8Array(h*d*4);for(g=i;g!==n;g+=r)for(m=a;m!==l;m+=o,p++)f=c[p],_[(m+h*g)*4+3]=255,_[(m+h*g)*4+2]=u[f*3+0],_[(m+h*g)*4+1]=u[f*3+1],_[(m+h*g)*4+0]=u[f*3+2];return _}function AEt(s,e,t,i,r,n,a,o,l){const c=t,u=s.width,h=s.height;let d,f=0,p,m;const g=new Uint8Array(u*h*4);for(m=i;m!==n;m+=r)for(p=a;p!==l;p+=o,f+=2){d=c[f+0]+(c[f+1]<<8);const _=((d&31744)>>10)*255/31|0,y=((d&992)>>5)*255/31|0,v=(d&31)*255/31|0;g[(p+u*m)*4+0]=_,g[(p+u*m)*4+1]=y,g[(p+u*m)*4+2]=v,g[(p+u*m)*4+3]=d&32768?0:255}return g}function bEt(s,e,t,i,r,n,a,o,l){const c=t,u=s.width,h=s.height;let d=0,f,p;const m=new Uint8Array(u*h*4);for(p=i;p!==n;p+=r)for(f=a;f!==l;f+=o,d+=3)m[(f+u*p)*4+3]=255,m[(f+u*p)*4+2]=c[d+0],m[(f+u*p)*4+1]=c[d+1],m[(f+u*p)*4+0]=c[d+2];return m}function CEt(s,e,t,i,r,n,a,o,l){const c=t,u=s.width,h=s.height;let d=0,f,p;const m=new Uint8Array(u*h*4);for(p=i;p!==n;p+=r)for(f=a;f!==l;f+=o,d+=4)m[(f+u*p)*4+2]=c[d+0],m[(f+u*p)*4+1]=c[d+1],m[(f+u*p)*4+0]=c[d+2],m[(f+u*p)*4+3]=c[d+3];return m}function SEt(s,e,t,i,r,n,a,o,l){const c=t,u=s.width,h=s.height;let d,f=0,p,m;const g=new Uint8Array(u*h*4);for(m=i;m!==n;m+=r)for(p=a;p!==l;p+=o,f++)d=c[f],g[(p+u*m)*4+0]=d,g[(p+u*m)*4+1]=d,g[(p+u*m)*4+2]=d,g[(p+u*m)*4+3]=255;return g}function EEt(s,e,t,i,r,n,a,o,l){const c=t,u=s.width,h=s.height;let d=0,f,p;const m=new Uint8Array(u*h*4);for(p=i;p!==n;p+=r)for(f=a;f!==l;f+=o,d+=2)m[(f+u*p)*4+0]=c[d+0],m[(f+u*p)*4+1]=c[d+0],m[(f+u*p)*4+2]=c[d+0],m[(f+u*p)*4+3]=c[d+1];return m}const gKe={GetTGAHeader:Yz,UploadContent:X1e,_getImageData8bits:xEt,_getImageData16bits:AEt,_getImageData24bits:bEt,_getImageData32bits:CEt,_getImageDataGrey8bits:SEt,_getImageDataGrey16bits:EEt};class _Ke{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=Yz(r);i(n.width,n.height,t.generateMipMaps,!1,()=>{X1e(t,r)})}}const TEt=Object.freeze(Object.defineProperty({__proto__:null,_TGATextureLoader:_Ke},Symbol.toStringTag,{value:"Module"}));class vKe{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=G1e(r),a=W1e(r,n),o=n.width*n.height,l=new Float32Array(o*4);for(let c=0;c{const c=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,c._uploadDataToTextureDirectly(t,l)})}}const MEt=Object.freeze(Object.defineProperty({__proto__:null,_HDRTextureLoader:vKe},Symbol.toStringTag,{value:"Module"}));function REt(){const s={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21};let e=null;onmessage=a=>{if(a.data.action==="init"){if(a.data.url)try{importScripts(a.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:a.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(a.data.action==="transcode"){const o=a.data.config,l=a.data.imageData,c=new BASIS.BasisFile(l),u=i(c);let h=a.data.ignoreSupportedFormats?null:t(a.data.config,u),d=!1;h===null&&(d=!0,h=u.hasAlpha?s.cTFBC3:s.cTFBC1);let f=!0;c.startTranscoding()||(f=!1);const p=[];for(let m=0;m>2&3],h[v++]=u[y>>4&3],h[v++]=u[y>>6&3]}}return h}}function IEt(s,e,t){return new Promise((i,r)=>{const n=a=>{a.data.action==="init"?(s.removeEventListener("message",n),i(s)):a.data.action==="error"&&r(a.data.error||"error initializing worker")};s.addEventListener("message",n),s.postMessage({action:"init",url:t?Me.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}class PEt{}class wEt{}var J2;(function(s){s[s.cTFETC1=0]="cTFETC1",s[s.cTFETC2=1]="cTFETC2",s[s.cTFBC1=2]="cTFBC1",s[s.cTFBC3=3]="cTFBC3",s[s.cTFBC4=4]="cTFBC4",s[s.cTFBC5=5]="cTFBC5",s[s.cTFBC7=6]="cTFBC7",s[s.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",s[s.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",s[s.cTFASTC_4x4=10]="cTFASTC_4x4",s[s.cTFATC_RGB=11]="cTFATC_RGB",s[s.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",s[s.cTFRGBA32=13]="cTFRGBA32",s[s.cTFRGB565=14]="cTFRGB565",s[s.cTFBGR565=15]="cTFBGR565",s[s.cTFRGBA4444=16]="cTFRGBA4444",s[s.cTFFXT1_RGB=17]="cTFFXT1_RGB",s[s.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",s[s.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",s[s.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",s[s.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(J2||(J2={}));const zv={JSModuleURL:`${Me._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Me._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},yKe=(s,e)=>{let t;switch(s){case J2.cTFETC1:t=36196;break;case J2.cTFBC1:t=33776;break;case J2.cTFBC4:t=33779;break;case J2.cTFASTC_4x4:t=37808;break;case J2.cTFETC2:t=37496;break;case J2.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let Hne=null,Uy=null,DEt=0;const LEt=!1,OEt=()=>(Hne||(Hne=new Promise((s,e)=>{Uy?s(Uy):Me.LoadFileAsync(Me.GetBabylonScriptURL(zv.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${REt})()`],{type:"application/javascript"}));Uy=new Worker(i),IEt(Uy,t,zv.JSModuleURL).then(s,e)}).catch(e)})),Hne),NEt=s=>{Uy=s},bZ=(s,e)=>{const t=s instanceof ArrayBuffer?new Uint8Array(s):s;return new Promise((i,r)=>{OEt().then(()=>{const n=DEt++,a=l=>{l.data.action==="transcode"&&l.data.id===n&&(Uy.removeEventListener("message",a),l.data.success?i(l.data):r("Transcode is not supported on this device"))};Uy.addEventListener("message",a);const o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),Uy.postMessage({action:"transcode",id:n,imageData:o,config:e,ignoreSupportedFormats:LEt},[o.buffer])},n=>{r(n)})})},dY=(s,e)=>{var i,r;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;s.isCube&&(t=(r=e._gl)==null?void 0:r.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,s,!0)},CZ=(s,e)=>{const t=s.getEngine();for(let i=0;i{t._releaseTexture(n),dY(s,t)})}else s._invertVScale=!s.invertY,s.width=r.width+3&-4,s.height=r.height+3&-4,s.samplingMode=2,dY(s,t),t._uploadDataToTextureDirectly(s,new Uint16Array(r.transcodedPixels.buffer),i,0,4,!0);else{s.width=r.width,s.height=r.height,s.generateMipMaps=e.fileInfo.images[i].levels.length>1;const n=Eee.GetInternalFormatFromBasisFormat(e.format,t);s.format=n,dY(s,t),e.fileInfo.images[i].levels.forEach((a,o)=>{t._uploadCompressedDataToTextureDirectly(s,n,a.width,a.height,a.transcodedPixels,i,o)}),t._features.basisNeedsPOT&&(At.Log2(s.width)%1!==0||At.Log2(s.height)%1!==0)&&(Me.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),s._cachedWrapU=xe.CLAMP_ADDRESSMODE,s._cachedWrapV=xe.CLAMP_ADDRESSMODE)}}},Eee={JSModuleURL:zv.JSModuleURL,WasmModuleURL:zv.WasmModuleURL,GetInternalFormatFromBasisFormat:yKe,TranscodeAsync:bZ,LoadTextureFromTranscodeResult:CZ};Object.defineProperty(Eee,"JSModuleURL",{get:function(){return zv.JSModuleURL},set:function(s){zv.JSModuleURL=s}});Object.defineProperty(Eee,"WasmModuleURL",{get:function(){return zv.WasmModuleURL},set:function(s){zv.WasmModuleURL=s}});class xKe{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,n){if(Array.isArray(e))return;const a=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};bZ(e,o).then(l=>{const c=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;CZ(t,l),t.getEngine()._setCubeMapTextureParams(t,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(l=>{Me.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,n&&n(l)})}loadData(e,t,i){const r=t.getEngine().getCaps(),n={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};bZ(e,n).then(a=>{const o=a.fileInfo.images[0].levels[0],l=a.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,a.format!==-1,()=>{CZ(t,a)})}).catch(a=>{Me.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Me.Warn(`Failed to transcode Basis file: ${a}`),i(0,0,!1,!1,()=>{},!0)})}}const FEt=Object.freeze(Object.defineProperty({__proto__:null,_BasisTextureLoader:xKe},Symbol.toStringTag,{value:"Module"})),AKe=4,$he=4,bKe=1,uP=2,BEt=8,SZ=65536,lMe=SZ>>3,kEt=16,zy=14,YB=(1<>-c-14,i[l|256]=1024>>-c-14|32768,r[l]=-c-1,r[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,r[l]=13,r[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,r[l]=24,r[l|256]=24):(i[l]=31744,i[l|256]=64512,r[l]=13,r[l|256]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;!(c&8388608);)c<<=1,u-=8388608;c&=-8388609,u+=947912704,n[l]=c|u}for(let l=1024;l<2048;++l)n[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function EZ(s,e){const t=new Uint8Array(s);let i=0;for(;t[e.value+i]!=0;)i+=1;const r=new TextDecoder().decode(t.slice(e.value,e.value+i));return e.value=e.value+i+1,r}function Ym(s,e){const t=s.getInt32(e.value,!0);return e.value+=AKe,t}function t_(s,e){const t=s.getUint32(e.value,!0);return e.value+=AKe,t}function Qz(s,e){const t=s.getUint8(e.value);return e.value+=bKe,t}function Kk(s,e){const t=s.getUint16(e.value,!0);return e.value+=uP,t}function Q1e(s,e){const t=s[e.value];return e.value+=bKe,t}function SKe(s,e){let t;return"getBigInt64"in DataView.prototype?t=Number(s.getBigInt64(e.value,!0)):t=s.getUint32(e.value+4,!0)+Number(s.getUint32(e.value,!0)<<32),e.value+=BEt,t}function Iu(s,e){const t=s.getFloat32(e.value,!0);return e.value+=$he,t}function EKe(s,e){return VEt(Kk(s,e))}function VEt(s){const e=(s&31744)>>10,t=s&1023;return(s>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function GEt(s){if(Math.abs(s)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");s=sa(s,-65504,65504),fY.floatView[0]=s;const e=fY.uint32View[0],t=e>>23&511;return fY.baseTable[t]+((e&8388607)>>fY.shiftTable[t])}function TKe(s,e){return GEt(Iu(s,e))}function WEt(s,e,t){const i=new TextDecoder().decode(new Uint8Array(s).slice(e.value,e.value+t));return e.value=e.value+t,i}function KEt(s,e){const t=Ym(s,e),i=t_(s,e);return[t,i]}function HEt(s,e){const t=t_(s,e),i=t_(s,e);return[t,i]}function jEt(s,e){const t=Iu(s,e),i=Iu(s,e);return[t,i]}function XEt(s,e){const t=Iu(s,e),i=Iu(s,e),r=Iu(s,e);return[t,i,r]}function YEt(s,e,t){const i=e.value,r=[];for(;e.valuen||(e[r++]=s[t++],r>n));)e[r++]=s[i++]}const JEt=20000630;function RKe(s,e){if(s.getUint32(0,!0)!=JEt)throw new Error("Incorrect OpenEXR format");const t=s.getUint8(4),i=s.getUint8(5),r={singleTile:!!(i&2),longName:!!(i&4),deepFormat:!!(i&8),multiPart:!!(i&16)};e.value=8;const n={};let a=!0;for(;a;){const o=EZ(s.buffer,e);if(!o)a=!1;else{const l=EZ(s.buffer,e),c=t_(s,e),u=MKe(s,e,l,c);u===void 0?fe.Warn(`Unknown header attribute type ${l}'.`):n[o]=u}}if(i&-5)throw new Error("Unsupported file format");return{version:t,spec:r,...n}}const IKe=16,eTt=1<>3]&1<<(r&7))&&(e[t++]=r);const i=t-1;for(;t>t&(1<>i;if(c=new Uint8Array([c])[0],o.value+c>l)return null;const u=a[o.value-1];for(;c-- >0;)a[o.value++]=u}else if(o.value0;--t){const i=e+A9[t]>>1;A9[t]=e,e=i}for(let t=0;t0&&(s[t]=i|A9[i]++<<6)}}function rTt(s,e,t,i,r,n){const a=e;let o=0,l=0;for(;i<=r;i++){if(a.value-e.value>t)return;let c=hMe(6,o,l,s,a);const u=c.l;if(o=c.c,l=c.lc,n[i]=u,u==CKe){if(a.value-e.value>t)throw new Error("Error in HufUnpackEncTable");c=hMe(8,o,l,s,a);let h=c.l+UEt;if(o=c.c,l=c.lc,i+h>r+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)n[i++]=0;i--}else if(u>=Zhe){let h=u-Zhe+2;if(i+h>r+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)n[i++]=0;i--}}iTt(n)}function wKe(s){return s&63}function DKe(s){return s>>6}function sTt(s,e,t,i){for(;e<=t;e++){const r=DKe(s[e]),n=wKe(s[e]);if(r>>n)throw new Error("Invalid table entry");if(n>zy){const a=i[r>>n-zy];if(a.len)throw new Error("Invalid table entry");if(a.lit++,a.p){const o=a.p;a.p=new Array(a.lit);for(let l=0;l0;o--){const l=i[(r<=zy;){const m=c>>u-zy&cMe,g=e[m];if(g.len){u-=g.len;const _=jne(g.lit,n,c,u,t,i,o,l,h);_&&(c=_.c,u=_.lc)}else{if(!g.p)throw new Error("hufDecode issues");let _;for(_=0;_=y&&DKe(s[g.p[_]])==(c>>u-y&(1<>=f,u-=f;u>0;){const p=e[c<=YB||c<0||c>=YB)throw new Error("Wrong HUF_ENCSIZE");const h=new Array(YB),d=new Array(Y1e);tTt(d);const f=i-(t.value-o);if(rTt(s,t,f,l,c,h),u>8*(i-(t.value-o)))throw new Error("Wrong hufUncompress");sTt(h,l,c,d),nTt(h,d,s,t,u,c,n,r,a)}function ede(s){return s&65535}function dMe(s){const e=ede(s);return e>32767?e-65536:e}function zI(s,e){const t=dMe(s),r=dMe(e),n=t+(r&1)+(r>>1),a=n,o=n-r;return{a,b:o}}function VI(s,e){const t=ede(s),i=ede(e),r=t-(i>>1)&uMe;return{a:i+r-eTt&uMe,b:r}}function OKe(s,e,t,i,r,n,a){const o=a<16384,l=t>r?r:t;let c=1,u,h;for(;c<=l;)c<<=1;for(c>>=1,u=c,c>>=1;c>=1;){h=0;const d=h+n*(r-u),f=n*c,p=n*u,m=i*c,g=i*u;let _,y,v,x;for(;h<=d;h+=p){let A=h;const b=h+i*(t-u);for(;A<=b;A+=g){const C=A+m,T=A+f,w=T+m;if(o){let P=zI(s[A+e],s[T+e]);_=P.a,v=P.b,P=zI(s[C+e],s[w+e]),y=P.a,x=P.b,P=zI(_,y),s[A+e]=P.a,s[C+e]=P.b,P=zI(v,x),s[T+e]=P.a,s[w+e]=P.b}else{let P=VI(s[A+e],s[T+e]);_=P.a,v=P.b,P=VI(s[C+e],s[w+e]),y=P.a,x=P.b,P=VI(_,y),s[A+e]=P.a,s[C+e]=P.b,P=VI(v,x),s[T+e]=P.a,s[w+e]=P.b}}if(t&c){const C=A+f;let T;o?T=zI(s[A+e],s[C+e]):T=VI(s[A+e],s[C+e]),_=T.a,s[C+e]=T.b,s[A+e]=_}}if(r&c){let A=h;const b=h+i*(t-u);for(;A<=b;A+=g){const C=A+m;let T;o?T=zI(s[A+e],s[C+e]):T=VI(s[A+e],s[C+e]),_=T.a,s[C+e]=T.b,s[A+e]=_}}u=c,c>>=1}return h}function NKe(s,e,t){for(let i=0;i0;){const n=r.getInt8(i++);if(n<0){const a=-n;e-=a+1;for(let o=0;o=lMe)throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");if(o<=l)for(let p=0;p0,bytesPerLine:0,outLineWidth:0,lines:0,scanlineBlockSize:0,inputSize:null,type:0,uncompress:null,getter:()=>0,format:5,outputChannels:0,decodeChannels:{},blockCount:null,byteArray:null,linearSpace:!1,textureType:0};switch(s.compression){case E1.NO_COMPRESSION:r.lines=1,r.uncompress=q1e;break;case E1.RLE_COMPRESSION:r.lines=1,r.uncompress=BKe;break;case E1.ZIPS_COMPRESSION:r.lines=1,r.uncompress=tde,await Me.LoadScriptAsync(wS.FFLATEUrl);break;case E1.ZIP_COMPRESSION:r.lines=16,r.uncompress=tde,await Me.LoadScriptAsync(wS.FFLATEUrl);break;case E1.PIZ_COMPRESSION:r.lines=32,r.uncompress=UKe;break;case E1.PXR24_COMPRESSION:r.lines=16,r.uncompress=kKe,await Me.LoadScriptAsync(wS.FFLATEUrl);break;default:throw new Error(E1[s.compression]+" is unsupported")}r.scanlineBlockSize=r.lines;const n={};for(const c of s.channels)switch(c.name){case"Y":case"R":case"G":case"B":case"A":n[c.name]=!0,r.type=c.pixelType}let a=!1;if(n.R&&n.G&&n.B)a=!n.A,r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(n.Y)r.outputChannels=1,r.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(r.type===1)switch(i){case D1.Float:r.getter=EKe,r.inputSize=uP;break;case D1.HalfFloat:r.getter=Kk,r.inputSize=uP;break}else if(r.type===2)switch(i){case D1.Float:r.getter=Iu,r.inputSize=$he;break;case D1.HalfFloat:r.getter=TKe,r.inputSize=$he}else throw new Error("Unsupported pixelType "+r.type+" for "+s.compression);r.blockCount=r.height/r.scanlineBlockSize;for(let c=0;cc:r.scanOrder=c=>r.height-1-c,r.outputChannels==4?(r.format=5,r.linearSpace=!0):(r.format=6,r.linearSpace=!1),r}function VKe(s,e,t,i){const r={value:0};for(let n=0;ns.height?s.height-a:s.scanlineBlockSize;const l=s.size=s.height)continue;const d=c*s.bytesPerLine,f=(s.height-1-h)*s.outLineWidth;for(let p=0;p{const u=t.getEngine();t.format=a.format,t.type=o.textureType,t.invertY=!1,t._gammaSpace=!a.linearSpace,o.byteArray&&u._uploadDataToTextureDirectly(t,o.byteArray,0,0,void 0,!0)})}}const aTt=Object.freeze(Object.defineProperty({__proto__:null,_ExrTextureLoader:GKe},Symbol.toStringTag,{value:"Module"}));class nv extends Rs{get isSupported(){var e;return((e=this._engine)==null?void 0:e.getCaps().drawBuffersExtension)??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,n,a,o,l,c,u){for(let h=0;h{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var t,i;const e=(t=this._renderTarget)==null?void 0:t.textures;if(e){for(let r=e.length-1;r>=0;r--)this._textures[r]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}class ide{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class p0{constructor(e,t,i,r){return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??$.UVKind,this.options.uvsOut=this.options.uvsOut??$.UVKind,this.options.layout=this.options.layout??p0.LAYOUT_STRIP,this.options.layout===p0.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,this.options.fillBlanks===!0&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!==0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??p0.SUBUV_WRAP,this.options.paddingMode===p0.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new Ze(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new we(1,1).divide(t);let r=0;const n=this._expecting,a=this.meshes.length,o=Object.keys(this.sets);for(let d=0;d{this._calculateMeshUVFrames(l,c,t,i,this.options.updateInputMeshes||!1)};for(let d=0;d{r++,g.update(!1);const A=_.getImageData(0,0,u,u),b=this.sets[x];if(b.getContext().putImageData(A,t.x*y.x,t.y*y.y),g.dispose(),b.update(!1),r==n){h(),e();return}},x=o[m]||"_blank";if(!p||p[x]===null)_.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(_.fillStyle=this.options.customFillColor),_.fillRect(0,0,u,u),v();else{const A=p[x],b=new Image;A instanceof Qf?b.src=A.getContext().canvas.toDataURL("image/png"):b.src=A.url,Me.SetCorsBehavior(b.src,b),b.onload=()=>{_.fillStyle="rgba(0,0,0,0)",_.fillRect(0,0,u,u),g.update(!1),_.setTransform(1,0,0,-1,0,0);const C=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let T=0;T<9;T++)_.drawImage(b,0,0,b.width,b.height,c+l*C[T],c+l*C[T+1]-u,l,l);break;case 1:for(let T=0;T{a.dispose&&a.dispose()};for(let a=0;a{try{if(this.meshes.length===0){e();return}let i=0;const r=n=>{if(i++,this.options.map){for(let a=0;a{r(o)})}}catch(i){return t(i)}})}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),n=Object.keys(this.options);try{for(let l=0;l{try{this.setFragment(this._texturePath)}catch{fe.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",r=new On;r.open("GET",i),r.addEventListener("load",()=>{if(r.status===200||r.responseText&&r.responseText.length>0)try{this._config=JSON.parse(r.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch{t()}else t()},!1),r.addEventListener("error",()=>{t()},!1);try{r.send()}catch{fe.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=t.getAnimationRatio()*.03,this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{})}clone(){return qe.Clone(()=>{const e=this.getScene(),t=this._texture,i=new Tee(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===13&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i},this)}}class cTt extends xe{constructor(e,t,i,r,n,a,o=!0,l=!1,c=xe.TRILINEAR_SAMPLINGMODE,u=0,h){super(null,a,!o,l),this.format=n,this._texture=a.getEngine().createRawTexture3D(e,t,i,r,n,o,l,c,null,u,h),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class J1e extends Rs{constructor(e,t,i,r){super(e,t,i,r,!0),this.refractionPlane=new Xl(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add(()=>{this.getScene().clipPlane=this.refractionPlane}),this.onAfterRenderObservable.add(()=>{this.getScene().clipPlane=null})}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new J1e(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}class uTt extends lv{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){var t;(t=this._renderTarget)==null||t.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){var t;(t=this._renderTarget)==null||t.dispose(!0),this._renderTarget=null,e||super.dispose()}}var rde;(function(s){s[s.Uniform=0]="Uniform",s[s.Attribute=1]="Attribute",s[s.Varying=2]="Varying",s[s.Undefined=3]="Undefined"})(rde||(rde={}));class ra extends o6{constructor(e,t,i,r,n){super(e,t,i),this._blockType=r,this._blockName=n,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof ra&&e._blockName===this._blockName?0:1}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class KKe extends qt{constructor(e){super(e,be.Vertex),this.registerInput("matricesIndices",ee.Vector4),this.registerInput("matricesWeights",ee.Vector4),this.registerInput("matricesIndicesExtra",ee.Vector4,!0),this.registerInput("matricesWeightsExtra",ee.Vector4,!0),this.registerInput("world",ee.Matrix),this.registerOutput("output",ee.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>cvt),void 0),Ue(()=>Promise.resolve().then(()=>xvt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>X2t),void 0),Ue(()=>Promise.resolve().then(()=>svt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="matricesIndices"&&t(r));i||(i=new nr("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="matricesWeights"&&t(r));i||(i=new nr("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.World&&t(r));i||(i=new nr("world"),i.setAsSystemValue(mr.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){ql(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&DJ(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const r=this._outputs[0],n=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 `,e.compilationString+=e._declareOutput(r)+` = ${n.associatedVariableName} * ${i}; `,e.compilationString+=`#else `,e.compilationString+=e._declareOutput(r)+` = ${n.associatedVariableName}; `,e.compilationString+=`#endif `,this}}ve("BABYLON.BonesBlock",KKe);class HKe extends qt{constructor(e){super(e,be.Vertex),this.registerInput("world0",ee.Vector4),this.registerInput("world1",ee.Vector4),this.registerInput("world2",ee.Vector4),this.registerInput("world3",ee.Vector4),this.registerInput("world",ee.Matrix,!0),this.registerOutput("output",ee.Matrix),this.registerOutput("instanceID",ee.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world0"&&t(r));i||(i=new nr("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world1"&&t(r));i||(i=new nr("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world2"&&t(r));i||(i=new nr("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world3"&&t(r));i||(i=new nr("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="world"&&t(r));i||(i=new nr("world"),i.setAsSystemValue(mr.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,n){let a=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),a=!0),n&&i.THIN_INSTANCES!==!!(n!=null&&n.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(n!=null&&n.getRenderingMesh().hasThinInstances)),a=!0),a&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],r=this._outputs[1],n=this.world0,a=this.world1,o=this.world2,l=this.world3;let c="mat4",u="gl_InstanceID",h="float";return e.shaderLanguage===1&&(c="mat4x4f",u="vertexInputs.instanceIndex",h="f32"),e.compilationString+=`#ifdef INSTANCES `,e.compilationString+=e._declareOutput(i)+` = ${c}(${n.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}, ${l.associatedVariableName}); `,e.compilationString+=`#ifdef THIN_INSTANCES `,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; `,e.compilationString+=`#endif `,t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(r)+` = ${h}(${u}); `:e.compilationString+=e._declareOutput(r)+` = 0.0; `,e.compilationString+=`#else `,e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName}; `,e.compilationString+=e._declareOutput(r)+` = 0.0; `,e.compilationString+=`#endif `,this}}ve("BABYLON.InstancesBlock",HKe);class e_e extends qt{constructor(e){super(e,be.Vertex),this.registerInput("position",ee.Vector3),this.registerInput("normal",ee.Vector3),this.registerInput("tangent",ee.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(ee.Color4|ee.Vector4|ee.Vector3),this.registerInput("uv",ee.Vector2),this.registerOutput("positionOutput",ee.Vector3),this.registerOutput("normalOutput",ee.Vector3),this.registerOutput("tangentOutput",ee.Vector4),this.registerOutput("uvOutput",ee.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>_vt),void 0),Ue(()=>Promise.resolve().then(()=>fvt),void 0),Ue(()=>Promise.resolve().then(()=>gvt),void 0),Ue(()=>Promise.resolve().then(()=>dvt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>tvt),void 0),Ue(()=>Promise.resolve().then(()=>Z2t),void 0),Ue(()=>Promise.resolve().then(()=>evt),void 0),Ue(()=>Promise.resolve().then(()=>$2t),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="position"&&t(r));i||(i=new nr("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="normal"&&t(r));i||(i=new nr("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="tangent"&&t(r));i||(i=new nr("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="uv"&&t(r));i||(i=new nr("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const r=e.morphTargetManager;r!=null&&r.isUsingTextureForTargets&&(r.numMaxInfluencers||r.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&LJ(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(I0(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){const n=this.position,a=this.normal,o=this.tangent,l=this.uv,c=this.positionOutput,u=this.normalOutput,h=this.tangentOutput,d=this.uvOutput,f=e,p=r.NUM_MORPH_INFLUENCERS,m=i.morphTargetManager,g=m&&m.supportsNormals&&r.NORMAL,_=m&&m.supportsTangents&&r.TANGENT,y=m&&m.supportsUVs&&r.UV1;let v="";m!=null&&m.isUsingTextureForTargets&&p>0&&(v+=`${f._declareLocalVar("vertexID",ee.Float)}; `),v+=`#ifdef MORPHTARGETS `;const x=f.shaderLanguage===1,A=x?"uniforms.":"";if(m!=null&&m.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) { `,v+=`if (i >= ${A}morphTargetCount) { break; } `,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${A}morphTargetTextureInfo.x; `,v+=`${c.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${A}morphTargetInfluences[i]; `,v+=`vertexID += 1.0; `,g&&(v+=`#ifdef MORPHTARGETS_NORMAL `,v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${a.associatedVariableName}) * ${A}morphTargetInfluences[i]; `,v+=`vertexID += 1.0; `,v+=`#endif `),y&&(v+=`#ifdef MORPHTARGETS_UV `,v+=`${d.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${l.associatedVariableName}) * ${A}morphTargetInfluences[i]; `,v+=`vertexID += 1.0; `,v+=`#endif `),_&&(v+=`#ifdef MORPHTARGETS_TANGENT `,v+=`${h.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${A}morphTargetInfluences[i]; `,o.type===ee.Vector4?v+=`${h.associatedVariableName}.w = ${o.associatedVariableName}.w; `:v+=`${h.associatedVariableName}.w = 1.; `,v+=`#endif `),v+=`} `;else for(let b=0;b0)for(let b=0;bPromise.resolve().then(()=>Kke),void 0),Ue(()=>Promise.resolve().then(()=>_At),void 0),Ue(()=>Promise.resolve().then(()=>AAt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>RUe),void 0),Ue(()=>Promise.resolve().then(()=>YAt),void 0),Ue(()=>Promise.resolve().then(()=>JAt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var a;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const t=this.color,i=this._outputs[0],r=`//${this.name}`,n=e.shaderLanguage===1?"Vec3":"";return e._emitFunctionFromInclude("helperFunctions",r),e._emitFunctionFromInclude("imageProcessingDeclaration",r),e._emitFunctionFromInclude("imageProcessingFunctions",r),(a=t.connectedPoint)!=null&&a.isConnected&&(t.connectedPoint.type===ee.Color4||t.connectedPoint.type===ee.Vector4?e.compilationString+=`${e._declareOutput(i)} = ${t.associatedVariableName}; `:e.compilationString+=`${e._declareOutput(i)} = vec4${e.fSuffix}(${t.associatedVariableName}, 1.0); `,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS `,this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName} = vec4${e.fSuffix}(toLinearSpace${n}(${t.associatedVariableName}.rgb), ${t.associatedVariableName}.a); `),e.compilationString+=`#else `,e.compilationString+=`#ifdef IMAGEPROCESSING `,this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName} = vec4${e.fSuffix}(toLinearSpace${n}(${t.associatedVariableName}.rgb), ${t.associatedVariableName}.a); `),e.compilationString+=`${i.associatedVariableName} = applyImageProcessing(${i.associatedVariableName}); `,e.compilationString+=`#endif `,e.compilationString+=`#endif `,this.rgb.hasEndpoints&&(e.compilationString+=e._declareOutput(this.rgb)+` = ${this.output.associatedVariableName}.xyz; `)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace}; `,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertInputToLinearSpace=e.convertInputToLinearSpace??!0}}F([Jt("Convert input to linear space",0,"ADVANCED")],t_e.prototype,"convertInputToLinearSpace",void 0);ve("BABYLON.ImageProcessingBlock",t_e);class uT extends qt{constructor(e){super(e,be.Fragment,!0),this.registerInput("normal",ee.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(ee.Color4|ee.Vector4|ee.Vector3),this.registerInput("tangent",ee.Vector4,!1),this.registerInput("world",ee.Matrix,!1),this.registerOutput("TBN",ee.Object,be.Fragment,new ra("TBN",this,1,uT,"TBNBlock")),this.registerOutput("row0",ee.Vector3,be.Fragment),this.registerOutput("row1",ee.Vector3,be.Fragment),this.registerOutput("row2",ee.Vector3,be.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return be.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(r=>r.isSystemValue&&r.systemValue===mr.World&&t(r));i||(i=new nr("world"),i.setAsSystemValue(mr.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="normal"&&t(r));i||(i=new nr("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="tangent"&&r.type===ee.Vector4&&t(r));i||(i=new nr("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var c,u,h,d;const r=this.normal,n=this.tangent;let a=r.isConnected;(c=r.connectInputBlock)!=null&&c.isAttribute&&!e.isVerticesDataPresent((u=r.connectInputBlock)==null?void 0:u.name)&&(a=!1);let o=n.isConnected;(h=n.connectInputBlock)!=null&&h.isAttribute&&!e.isVerticesDataPresent((d=n.connectInputBlock)==null?void 0:d.name)&&(o=!1);const l=a&&o;i.setValue("TBNBLOCK",l,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,r=this.world,n=this.TBN,a=this.row0,o=this.row1,l=this.row2,c=e.shaderLanguage===1,u=c?"mat3x3f":"mat3",h=c?"f":"";return e.target===be.Fragment&&(e.compilationString+=` // ${this.name} ${e._declareLocalVar("tbnNormal",ee.Vector3)} = normalize(${t.associatedVariableName}).xyz; ${e._declareLocalVar("tbnTangent",ee.Vector3)} = normalize(${i.associatedVariableName}.xyz); ${e._declareLocalVar("tbnBitangent",ee.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; ${c?"var":"mat3"} ${n.associatedVariableName} = ${u}(${r.associatedVariableName}[0].xyz, ${r.associatedVariableName}[1].xyz, ${r.associatedVariableName}[2].xyz) * ${u}(tbnTangent, tbnBitangent, tbnNormal); `,a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${h}(${n.associatedVariableName}[0][0], ${n.associatedVariableName}[0][1], ${n.associatedVariableName}[0][2]); `),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${h}(${n.associatedVariableName}[1[0], ${n.associatedVariableName}[1][1], ${n.associatedVariableName}[1][2]); `),l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = vec3${h}(${n.associatedVariableName}[2][0], ${n.associatedVariableName}[2][1], ${n.associatedVariableName}[2][2]); `),e.sharedData.blocksWithDefines.push(this)),this}}ve("BABYLON.TBNBlock",uT);class nD extends qt{constructor(e){super(e,be.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",ee.Vector4,!1),this.registerInput("worldNormal",ee.Vector4,!1),this.registerInput("worldTangent",ee.Vector4,!0),this.registerInput("uv",ee.Vector2,!1),this.registerInput("normalMapColor",ee.Color3,!1),this.registerInput("strength",ee.Float,!1),this.registerInput("viewDirection",ee.Vector3,!0),this.registerInput("parallaxScale",ee.Float,!0),this.registerInput("parallaxHeight",ee.Float,!0),this.registerInput("TBN",ee.Object,!0,be.VertexAndFragment,new ra("TBN",this,0,uT,"TBNBlock")),this.registerInput("world",ee.Matrix,!0),this.registerOutput("output",ee.Vector4),this.registerOutput("uvOffset",ee.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>FCt),void 0),Ue(()=>Promise.resolve().then(()=>dCt),void 0),Ue(()=>Promise.resolve().then(()=>fCt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>N6t),void 0),Ue(()=>Promise.resolve().then(()=>c6t),void 0),Ue(()=>Promise.resolve().then(()=>u6t),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}prepareDefines(e,t,i){const r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,n=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",n,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="uv"&&t(r));i||(i=new nr("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new nr("strength");i.value=1,i.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,r=this.worldPosition,n=this.worldNormal,a=this.worldTangent,o=e.shaderLanguage===1,l=o?"mat3x3f":"mat3",c=o?"f":"",u=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,ee.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,ee.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,ee.Matrix);let h=null;this.normalMapColor.connectedPoint&&(h=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const d=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&h||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),f=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",p=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?` #if !defined(NORMALXYSCALE) 1.0/ #endif ${e._emitFloat(this.strength.connectInputBlock.value)}`:` #if !defined(NORMALXYSCALE) 1.0/ #endif ${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const m={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},g={search:/varying mat3 vTBN;/g,replace:""},_={search:/uniform mat4 normalMatrix;/g,replace:""},y=this.TBN;y.isConnected?e.compilationString+=` #ifdef TBNBLOCK ${o?"var":"mat3"} vTBN = ${y.associatedVariableName}; #endif `:a.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",ee.Vector3)} = normalize(${n.associatedVariableName}.xyz); `,e.compilationString+=`${e._declareLocalVar("tbnTangent",ee.Vector3)} = normalize(${a.associatedVariableName}.xyz); `,e.compilationString+=`${e._declareLocalVar("tbnBitangent",ee.Vector3)} = cross(tbnNormal, tbnTangent) * ${o?"uniforms.":""}${this._tangentCorrectionFactorName}; `,e.compilationString+=`${o?"var":"mat3"} vTBN = ${l}(tbnTangent, tbnBitangent, tbnNormal); `);let v=[m,g,_];o&&(v.push({search:/varying vTBN0: vec3f;/g,replace:""}),v.push({search:/varying vTBN1: vec3f;/g,replace:""}),v.push({search:/varying vTBN2: vec3f;/g,replace:""})),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:v});const x=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":`#define inline vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`,A=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,b=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",C=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:A,replace:x},{search:C,replace:b},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const T=o?`textureSample(${h}, ${h+"Sampler"}`:`texture2D(${h}`,w=!d||!h?this.normalMapColor.associatedVariableName:`${T}, ${i.associatedVariableName} + uvOffset).xyz`,P=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(P,ee.Vector3)+` = vec3${c}(0.); `,v=[{search:new RegExp(`texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\)`,"g"),replace:`${w}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",ee.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:new RegExp(`perturbNormal\\(TBN,texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\+uvOffset\\).xyz,${o?"uniforms.":""}vBumpInfos.y\\)`,"g"),replace:`perturbNormal(TBN, ${w}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?d&&this.useParallaxOcclusion?`${h}, ${h+"Sampler"}`:"bump, bumpSampler":d&&this.useParallaxOcclusion?h:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${d?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vBumpInfos.y/g,replace:p},{search:/vBumpInfos.z/g,replace:f},{search:/normalW=/g,replace:P+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${l}(normalMatrix) * `+P},{search:/normalW/g,replace:n.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:d?this.viewDirection.associatedVariableName:`vec3${c}(0.)`},m],o?(v.push({search:/fragmentInputs.vBumpUV/g,replace:i.associatedVariableName}),v.push({search:/input.vPositionW/g,replace:r.associatedVariableName+".xyz"}),v.push({search:/uniforms.vTangentSpaceParams/g,replace:u+this._tangentSpaceParameterName}),v.push({search:/var TBN: mat3x3f=mat3x3\(input.vTBN0,input.vTBN1,input.vTBN2\);/g,replace:"var TBN = vTBN;"})):(v.push({search:/vBumpUV/g,replace:i.associatedVariableName}),v.push({search:/vPositionW/g,replace:r.associatedVariableName+".xyz"}),v.push({search:/vTangentSpaceParams/g,replace:u+this._tangentSpaceParameterName})),e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:v}),e.compilationString+=e._declareOutput(this.output)+` = vec4${c}(${P}, 0.); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; `;return e+=`${this._codeVariableName}.invertY = ${this.invertY}; `,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; `,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; `,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}F([Jt("Invert X axis",0,"PROPERTIES",{notifiers:{update:!1}})],nD.prototype,"invertX",void 0);F([Jt("Invert Y axis",0,"PROPERTIES",{notifiers:{update:!1}})],nD.prototype,"invertY",void 0);F([Jt("Use parallax occlusion",0)],nD.prototype,"useParallaxOcclusion",void 0);F([Jt("Object Space Mode",0,"PROPERTIES",{notifiers:{update:!1}})],nD.prototype,"useObjectSpaceNormalMap",void 0);ve("BABYLON.PerturbNormalBlock",nD);class XKe extends qt{constructor(e){super(e,be.Fragment,!0),this.registerInput("value",ee.Float,!0),this.registerInput("cutoff",ee.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,!(!this.cutoff.isConnected||!this.value.isConnected))return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; } `,this}}ve("BABYLON.DiscardBlock",XKe);class YKe extends qt{constructor(e){super(e,be.Fragment),this.registerOutput("output",ee.Float,be.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===be.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",e.shaderLanguage===0?"gl_FrontFacing":"fragmentInputs.frontFacing")}; `,this}}ve("BABYLON.FrontFacingBlock",YKe);class QKe extends qt{constructor(e){super(e,be.Fragment),this.registerInput("input",ee.AutoDetect,!1),this.registerOutput("dx",ee.BasedOnInput),this.registerOutput("dy",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let r="dFdx",n="dFdy";return e.shaderLanguage===1&&(r="dpdx",n="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${r}(${this.input.associatedVariableName}); `),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${n}(${this.input.associatedVariableName}); `),this}}ve("BABYLON.DerivativeBlock",QKe);class $Ke extends qt{constructor(e){super(e,be.Fragment),this.registerOutput("xy",ee.Vector2,be.Fragment),this.registerOutput("xyz",ee.Vector3,be.Fragment),this.registerOutput("xyzw",ee.Vector4,be.Fragment),this.registerOutput("x",ee.Float,be.Fragment),this.registerOutput("y",ee.Float,be.Fragment),this.registerOutput("z",ee.Float,be.Fragment),this.registerOutput("w",ee.Float,be.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=e.shaderLanguage===1?"fragmentInputs.position":"gl_FragCoord";for(const r of this._outputs)r.hasEndpoints&&(t+=`${e._declareOutput(r)} = ${i}.${r.name}; `);return t}_buildBlock(e){if(super._buildBlock(e),e.target===be.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}ve("BABYLON.FragCoordBlock",$Ke);class ZKe extends qt{constructor(e){super(e,be.Fragment),this.registerOutput("xy",ee.Vector2,be.Fragment),this.registerOutput("x",ee.Float,be.Fragment),this.registerOutput("y",ee.Float,be.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const r of this._outputs)r.hasEndpoints&&(i+=`${e._declareOutput(r)} = ${t}.${r.name}; `);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===be.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,ee.Vector2);const t=e.shaderLanguage===1?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}ve("BABYLON.ScreenSizeBlock",ZKe);class qKe extends qt{constructor(e){super(e,be.Fragment),this.registerInput("vector",ee.AutoDetect),this.registerInput("worldViewProjection",ee.Matrix),this.registerOutput("output",ee.Vector2),this.registerOutput("x",ee.Float),this.registerOutput("y",ee.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.WorldViewProjection&&t(r));i||(i=new nr("worldViewProjection"),i.setAsSystemValue(mr.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const r=i.associatedVariableName,n=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case ee.Vector3:e.compilationString+=`${e._declareLocalVar(n,ee.Vector4)} = ${r} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0); `;break;case ee.Vector4:e.compilationString+=`${e._declareLocalVar(n,ee.Vector4)} = ${r} * ${t.associatedVariableName}; `;break}return e.compilationString+=`${n} = vec4${e.fSuffix}(${n}.xy / ${n}.w, ${n}.zw);`,e.compilationString+=`${n} = vec4${e.fSuffix}(${n}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${n}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n}.xy; `),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x; `),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y; `),this}}ve("BABYLON.ScreenSpaceBlock",qKe);class JKe extends qt{constructor(e){super(e,be.Fragment),this.registerInput("input",ee.Vector2),this.registerInput("strength",ee.Float),this.registerInput("center",ee.Vector2),this.registerInput("offset",ee.Vector2),this.registerOutput("output",ee.Vector2),this.registerOutput("x",ee.Float),this.registerOutput("y",ee.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new nr("center");e.value=new we(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new nr("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new nr("offset");e.value=new we(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),n=e._getFreeVariableName("y"),a=e._getFreeVariableName("result");return e.compilationString+=` ${e._declareLocalVar(t,ee.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; ${e._declareLocalVar(i,ee.Float)} = ${this.strength.associatedVariableName} * length(${t}); ${e._declareLocalVar(r,ee.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; ${e._declareLocalVar(n,ee.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; ${e._declareLocalVar(a,ee.Vector2)} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${n} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${a}; `),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${a}.x; `),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${a}.y; `),this}}ve("BABYLON.TwirlBlock",JKe);class $z extends qt{constructor(e){super(e,be.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",ee.Float),this.registerInput("worldPosition",ee.Vector3),this.registerInput("worldNormal",ee.Vector3),this.registerInput("worldTangent",ee.AutoDetect,!0),this.registerOutput("output",ee.Vector4),this.registerOutput("xyz",ee.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===1,r=e.fSuffix;!this.generateInWorldSpace&&!this.worldTangent.isConnected&&fe.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const n=this.generateInWorldSpace?"":` vec3 biTangent = cross(norm, tgt); mat3 TBN = mat3(tgt, biTangent, norm); `,a=this.generateInWorldSpace?"":` result = TBN * result; result = result * vec3(0.5) + vec3(0.5); `;let o=` vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) { vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"} vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"} ${n} vec3 worlddX = dFdx(position); vec3 worlddY = dFdy(position); vec3 crossX = cross(norm, worlddX); vec3 crossY = cross(norm, worlddY); float d = abs(dot(crossY, worlddX)); vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); inToNormal.y *= -1.0; vec3 result = normalize((d * norm) - inToNormal); ${a} return vec4(result, 0.); }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${r}(0.)`}.xyz, ${this.worldNormal.associatedVariableName}); `,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz; `),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; `,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; `,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; `,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}F([Jt("Generate in world space instead of tangent space",0,"PROPERTIES",{notifiers:{update:!0}})],$z.prototype,"generateInWorldSpace",void 0);F([Jt("Force normalization for the worldNormal input",0,"PROPERTIES",{notifiers:{update:!0}})],$z.prototype,"automaticNormalizationNormal",void 0);F([Jt("Force normalization for the worldTangent input",0,"PROPERTIES",{notifiers:{update:!0}})],$z.prototype,"automaticNormalizationTangent",void 0);ve("BABYLON.HeightToNormalBlock",$z);class eHe extends qt{constructor(e){super(e,be.Fragment,!0),this.registerInput("depth",ee.Float,!0),this.registerInput("worldPos",ee.Vector4,!0),this.registerInput("viewProjection",ee.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===0?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName}; `:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` ${e._declareLocalVar("p",ee.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; ${e._declareLocalVar("v",ee.Float)} = p.z / p.w; #ifndef IS_NDC_HALF_ZRANGE v = v * 0.5 + 0.5; #endif ${t} = v; `:fe.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}ve("BABYLON.FragDepthBlock",eHe);class tHe extends qt{constructor(e){super(e,be.Fragment),this.registerInput("worldPosition",ee.Vector4,!1),this.registerInput("viewProjection",ee.Matrix,!1),this.registerInput("worldNormal",ee.AutoDetect,!0),this.registerOutput("depth",ee.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>uxt),void 0),Ue(()=>Promise.resolve().then(()=>Jyt),void 0),Ue(()=>Promise.resolve().then(()=>sxt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>Fxt),void 0),Ue(()=>Promise.resolve().then(()=>Wyt),void 0),Ue(()=>Promise.resolve().then(()=>vxt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=e.shaderLanguage===1;e._emitUniformFromString("biasAndScaleSM",ee.Vector3),e._emitUniformFromString("lightDataSM",ee.Vector3),e._emitUniformFromString("depthValuesSM",ee.Vector2),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`${e._declareLocalVar("worldPos",ee.Vector4)} = ${this.worldPosition.associatedVariableName}; `,e.compilationString+=`${e._declareLocalVar("vPositionWSM",ee.Vector3)}; `,e.compilationString+=`${e._declareLocalVar("vDepthMetricSM",ee.Float)} = 0.0; `,e.compilationString+=`${e._declareLocalVar("zSM",ee.Float)}; `,this.worldNormal.isConnected&&(e.compilationString+=`${e._declareLocalVar("vNormalW",ee.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`${e._declareLocalVar("clipPos",ee.Vector4)} = ${this.viewProjection.associatedVariableName} * worldPos; `,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"},{search:/vertexOutputs.position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]});const r=i?"fragmentOutputs.fragDepth":"gl_FragDepth";return e.compilationString+=` #if SM_DEPTHTEXTURE == 1 #ifdef IS_NDC_HALF_ZRANGE ${r} = (clipPos.z / clipPos.w); #else ${r} = (clipPos.z / clipPos.w) * 0.5 + 0.5; #endif #endif `,e.compilationString+=`${e._declareOutput(this.depth)} = vec3${e.fSuffix}(depthSM, 1., 1.); `,this}}ve("BABYLON.ShadowMapBlock",tHe);class iHe extends qt{constructor(e){super(e,be.Fragment,!0),this.registerInput("viewDepth",ee.Float,!0),this.registerInput("worldPosition",ee.AutoDetect,!0),this.registerInput("viewNormal",ee.AutoDetect,!0),this.registerInput("reflectivity",ee.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4|ee.Color3|ee.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_getFragData(e,t){return e?`fragmentOutputs.fragData${t}`:`gl_FragData[${t}]`}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,n=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const a=`//${this.name}`,o=e._getShaderType(ee.Vector4),l=e.shaderLanguage===1;return e._emitFunctionFromInclude("helperFunctions",a),e.compilationString+=`#if defined(PREPASS)\r `,e.compilationString+=l?`var fragData: array, SCENE_MRT_COUNT>;\r `:`vec4 fragData[SCENE_MRT_COUNT];\r `,e.compilationString+=`#ifdef PREPASS_DEPTH\r `,r.connectedPoint?e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${o}(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r `:e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${o}(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_POSITION\r `,t.connectedPoint?e.compilationString+=`fragData[PREPASS_POSITION_INDEX] = ${o}(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===ee.Vector4?t.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` fragData[PREPASS_POSITION_INDEX] = ${o}(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_NORMAL\r `,i.connectedPoint?e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${o}(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===ee.Vector4?i.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${o}(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r `,n.connectedPoint?e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${o}(${n.associatedVariableName}.rgb, ${n.connectedPoint.type===ee.Vector4?n.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${o}(0.0, 0.0, 0.0, 1.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 1\r `,e.compilationString+=`${this._getFragData(l,1)} = fragData[1];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 2\r `,e.compilationString+=`${this._getFragData(l,2)} = fragData[2];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 3\r `,e.compilationString+=`${this._getFragData(l,3)} = fragData[3];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 4\r `,e.compilationString+=`${this._getFragData(l,4)} = fragData[4];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 5\r `,e.compilationString+=`${this._getFragData(l,5)} = fragData[5];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 6\r `,e.compilationString+=`${this._getFragData(l,6)} = fragData[6];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 7\r `,e.compilationString+=`${this._getFragData(l,7)} = fragData[7];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#endif\r `,this}}ve("BABYLON.PrePassOutputBlock",iHe);class rHe extends qt{constructor(e){super(e,be.VertexAndFragment,!1),this.registerInput("worldPosition",ee.Vector4,!1,be.Vertex),this.registerInput("view",ee.Matrix,!1,be.Vertex),this.registerInput("input",ee.AutoDetect,!1,be.Fragment),this.registerInput("fogColor",ee.AutoDetect,!1,be.Fragment),this.registerOutput("output",ee.Color3,be.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Ue(()=>Promise.resolve().then(()=>bAt),void 0):await Ue(()=>Promise.resolve().then(()=>ebt),void 0),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.View&&t(r));i||(i=new nr("view"),i.setAsSystemValue(mr.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.FogColor&&t(r));i||(i=new nr("fogColor",void 0,ee.Color3),i.setAsSystemValue(mr.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const r=e.getScene();i.setValue("FOG",t.fogEnabled&&wJ(e,r))}bind(e,t,i){if(!i)return;const r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===be.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",r="";e.shaderLanguage===1?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",r="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const n=e._getFreeVariableName("fog"),a=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const l=this._outputs[0];e._emitUniformFromString(this._fogParameters,ee.Vector4),e.compilationString+=`#ifdef FOG `,e.compilationString+=`${e._declareLocalVar(n,ee.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${r}${this._fogParameters}); `,e.compilationString+=e._declareOutput(l)+` = ${n} * ${a.associatedVariableName}.rgb + (1.0 - ${n}) * ${o.associatedVariableName}.rgb; `,e.compilationString+=`#else ${e._declareOutput(l)} = ${a.associatedVariableName}.rgb; `,e.compilationString+=`#endif `}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,ee.Vector3);const r=e.shaderLanguage===1?"vertexOutputs.":"";e.compilationString+=`${r}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; `}return this}}ve("BABYLON.FogBlock",rHe);class TZ extends qt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,fe.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?be.Fragment:be.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?be.Fragment:be.Vertex}constructor(e){super(e,be.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",ee.Vector4,!1,be.Vertex),this.registerInput("worldNormal",ee.Vector4,!1,be.Fragment),this.registerInput("cameraPosition",ee.Vector3,!1,be.Fragment),this.registerInput("glossiness",ee.Float,!0,be.Fragment),this.registerInput("glossPower",ee.Float,!0,be.Fragment),this.registerInput("diffuseColor",ee.Color3,!0,be.Fragment),this.registerInput("specularColor",ee.Color3,!0,be.Fragment),this.registerInput("view",ee.Matrix,!0),this.registerOutput("diffuseOutput",ee.Color3,be.Fragment),this.registerOutput("specularOutput",ee.Color3,be.Fragment),this.registerOutput("shadow",ee.Float,be.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>CAt),void 0),Ue(()=>Promise.resolve().then(()=>vAt),void 0),Ue(()=>Promise.resolve().then(()=>oAt),void 0),Ue(()=>Promise.resolve().then(()=>Kke),void 0),Ue(()=>Promise.resolve().then(()=>yAt),void 0),Ue(()=>Promise.resolve().then(()=>xAt),void 0),Ue(()=>Promise.resolve().then(()=>dAt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>QAt),void 0),Ue(()=>Promise.resolve().then(()=>tbt),void 0),Ue(()=>Promise.resolve().then(()=>$At),void 0),Ue(()=>Promise.resolve().then(()=>FAt),void 0),Ue(()=>Promise.resolve().then(()=>NAt),void 0),Ue(()=>Promise.resolve().then(()=>RUe),void 0),Ue(()=>Promise.resolve().then(()=>ZAt),void 0),Ue(()=>Promise.resolve().then(()=>qAt),void 0),Ue(()=>Promise.resolve().then(()=>VAt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.CameraPosition&&t(r));i||(i=new nr("cameraPosition"),i.setAsSystemValue(mr.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const r=e.getScene();if(!this.light)du(r,e,i,!0,t.maxSimultaneousLights);else{const n={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};pz(r,e,this.light,this._lightId,i,!0,n),n.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,r){for(let n=0;n=0;gz(n,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+n],r,a)}}bind(e,t,i){if(!i)return;const r=i.getScene();this.light?fz(this.light,this._lightId,r,e,!0):hu(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,ee.Vector4)&&(e.compilationString+=(e.shaderLanguage===1?"vertexOutputs.":"")+`${r} = ${t.associatedVariableName}; `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",ee.Vector4)} = ${t.associatedVariableName}; `,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",ee.Matrix)} = ${this.view.associatedVariableName}; `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===1,i=t?"f":"",r=`//${this.name}`;if(e.target!==be.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const n=e.shaderLanguage===1?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const a=this.worldPosition;let o=a.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,ee.Vector3)}; `,r),e.compilationString+=`${o} = ${a.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${a.associatedVariableName}`:void 0})):o=n+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",r),e._emitFunctionFromInclude("lightsFragmentFunctions",r,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",r,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),this._injectUBODeclaration(e),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",ee.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o}); `),e.compilationString+=t?`var info: lightingInfo; `:`lightingInfo info; `,e.compilationString+=`${e._declareLocalVar("shadow",ee.Float)} = 1.; `,e.compilationString+=`${e._declareLocalVar("aggShadow",ee.Float)} = 0.; `,e.compilationString+=`${e._declareLocalVar("numLights",ee.Float)} = 0.; `,e.compilationString+=`${e._declareLocalVar("glossiness",ee.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; `,e.compilationString+=`${e._declareLocalVar("diffuseBase",ee.Vector3)} = vec3${i}(0., 0., 0.); `,e.compilationString+=`${e._declareLocalVar("specularBase",ee.Vector3)} = vec3${i}(0., 0., 0.); `,e.compilationString+=`${e._declareLocalVar("normalW",ee.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz; `),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:o+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${o}.xyz`}),this._lightId===0&&(e.compilationString+=`aggShadow = aggShadow / numLights; `);const l=this.diffuseOutput,c=this.specularOutput;return e.compilationString+=e._declareOutput(l)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; `,c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; `),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+` = aggShadow; `),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}F([Jt("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:TZ._OnGenerateOnlyFragmentCodeChanged}})],TZ.prototype,"generateOnlyFragmentCode",void 0);ve("BABYLON.LightBlock",TZ);class y0 extends qt{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Rt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,be.VertexAndFragment),this.registerOutput("source",ee.Object,be.VertexAndFragment,new ra("source",this,1,y0,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===be.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); `,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; `,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; `,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; `,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; `,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; `,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; `,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; `,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; `,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,r){super._deserialize(e,t,i,r),e.texture&&!Ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(e.texture.url.indexOf("data:")===0?i="":r&&(e.texture.url=r(e.texture.url),e.texture.name=e.texture.url),this.texture=xe.Parse(e.texture,t,i))}}ve("BABYLON.ImageSourceBlock",y0);class jk extends qt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)==null?void 0:e.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Rt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}static _IsPrePassTextureBlock(e){return(e==null?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return jk._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!jk._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const t=this.texture.getScene()??Rt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const t=this.texture.getScene()??Rt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?be.Fragment:be.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",ee.AutoDetect,!1,be.VertexAndFragment),this.registerInput("source",ee.Object,!0,be.VertexAndFragment,new ra("source",this,0,y0,"ImageSourceBlock")),this.registerInput("layer",ee.Float,!0),this.registerInput("lod",ee.Float,!0),this.registerOutput("rgba",ee.Color4,be.Neutral),this.registerOutput("rgb",ee.Color3,be.Neutral),this.registerOutput("r",ee.Float,be.Neutral),this.registerOutput("g",ee.Float,be.Neutral),this.registerOutput("b",ee.Float,be.Neutral),this.registerOutput("a",ee.Float,be.Neutral),this.registerOutput("level",ee.Float,be.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector2|ee.Vector3|ee.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return be.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return be.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===be.Fragment)return be.Fragment;if(e.target===be.Vertex)return be.VertexAndFragment;if(e.target===be.Neutral||e.target===be.VertexAndFragment){const t=e.ownerBlock;if(t.target===be.Fragment)return be.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return be.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===Eu.PostProcess){const i=e.getBlockByPredicate(r=>r.name==="uv"&&t(r));i&&i.connectTo(this)}else{const i=e.mode===Eu.Particle?"particle_uv":"uv";let r=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name===i&&t(n));r||(r=new nr("uv"),r.setAsAttribute(i)),r.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&this._mainUVDefineName!==void 0&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,n=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,n,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),i[this._mainUVDefineName]==null&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return this._isSourcePrePass?!0:!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==be.Fragment}_injectVertexCode(e){const t=this.uv;this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.declarationVariableName.toUpperCase(),this._mainUVName="vMain"+t.declarationVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,ee.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,ee.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,ee.Matrix,this._defineName);const i=e._getShaderType(ee.Vector4),r=e._getShaderType(ee.Vector2);e.compilationString+=`#ifdef ${this._defineName} `,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${r}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0)); `,e.compilationString+=`#elif defined(${this._mainUVDefineName}) `;let n="";if(e.shaderLanguage===1&&t.isConnectedToInputBlock&&t.associatedVariableName.indexOf("vertexInputs.")===-1&&(n="vertexInputs."),e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${n}${t.associatedVariableName}.xy; `,e.compilationString+=`#endif `,!!this._outputs.some(a=>a.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const a of this._outputs)a.hasEndpoints&&a.name!=="level"&&this._writeOutput(e,a,a.name,!0)}}_getUVW(e){var n,a,o,l;let t=e;const i=((a=(n=this._texture)==null?void 0:n._texture)==null?void 0:a.is2DArray)??!1,r=((l=(o=this._texture)==null?void 0:o._texture)==null?void 0:l.is3D)??!1;if(i){const c=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${c})`}else if(r){const c=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${c})`}return t}_samplerFunc(e){return e.shaderLanguage===1?e.target===be.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(t.shaderLanguage===1){const i=t.target===be.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName} `,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)}; `,e.compilationString+=`#elif defined(${this._mainUVDefineName}) `,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix}; `,e.compilationString+=`#endif `}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===be.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===be.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix}; `;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName} ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); #endif `),e.compilationString+=`#ifdef ${this._gammaDefineName} ${t.associatedVariableName} = ${e._toLinearSpace(t)}; #endif `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===be.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===be.Fragment){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `,this._generateConversionCode(e,t,i);return}let n="";this.disableLevelMultiplication||(n=` * ${(e.shaderLanguage===1?"uniforms.":"")+this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${n}; `,this._generateConversionCode(e,t,i)}_buildBlock(e){var i,r,n,a;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===be.Vertex||this._fragmentOnly||e.target===be.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===be.Fragment||this._isMixed&&e.target===be.Vertex){if(!this._imageSource){const o=e._getFreeVariableName(this.name);this._samplerName=o+"Texture",(r=(i=this._texture)==null?void 0:i._texture)!=null&&r.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==be.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(o=>o.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((a=(n=this._texture)==null?void 0:n._texture)!=null&&a.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,ee.Float),this._writeTextureRead(e);for(const o of this._outputs)o.hasEndpoints&&o.name!=="level"&&this._writeOutput(e,o,o.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; `,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; `,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; `,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); `,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; `,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; `,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; `,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; `,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; `,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; `,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; `,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; `,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,r){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(e.texture.url.indexOf("data:")===0?i="":r&&(e.texture.url=r(e.texture.url),e.texture.name=e.texture.url),this.texture=xe.Parse(e.texture,t,i))}}ve("BABYLON.TextureBlock",jk);class lw extends qt{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Rt.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?be.Fragment:be.VertexAndFragment)}constructor(e){super(e,be.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Ue(()=>Promise.resolve().then(()=>gAt),void 0):await Ue(()=>Promise.resolve().then(()=>XAt),void 0),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name==="position"&&t(r));i||(i=new nr("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.World&&t(r));i||(i=new nr("world"),i.setAsSystemValue(mr.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.View&&t(r));i||(i=new nr("view"),i.setAsSystemValue(mr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this._getTexture();!r||!r.getTextureMatrix||(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,r.coordinatesMode===0,!0),i.setValue(this._defineSkyboxName,r.coordinatesMode===5,!0),i.setValue(this._defineCubicName,r.coordinatesMode===3||r.coordinatesMode===6,!0),i.setValue("INVERTCUBICMAP",r.coordinatesMode===6,!0),i.setValue(this._defineSphericalName,r.coordinatesMode===1,!0),i.setValue(this._definePlanarName,r.coordinatesMode===2,!0),i.setValue(this._defineProjectionName,r.coordinatesMode===4,!0),i.setValue(this._defineEquirectangularName,r.coordinatesMode===7,!0),i.setValue(this._defineEquirectangularFixedName,r.coordinatesMode===8,!0),i.setValue(this._defineMirroredEquirectangularFixedName,r.coordinatesMode===9,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,r){const n=this._getTexture();if(!(!i||!n)&&(e.setMatrix(this._reflectionMatrixName,n.getReflectionTextureMatrix()),n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n),n.boundingBoxSize)){const a=n;e.setVector3(this._reflectionPositionName,a.boundingBoxPosition),e.setVector3(this._reflectionSizeName,a.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===be.Vertex)return"";const t=e.shaderLanguage===1;this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,ee.Matrix);let i="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const r=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(r,ee.Vector4))&&(this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(r,ee.Vector4)} = ${this.worldPosition.associatedVariableName}; `:i+=`${t?"vertexOutputs.":""}${r} = ${this.worldPosition.associatedVariableName}; `),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,ee.Vector3,this._defineSkyboxName))&&(i+=`#ifdef ${this._defineSkyboxName} `,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._positionUVWName,ee.Vector3)} = ${this.position.associatedVariableName}.xyz; `:i+=`${t?"vertexOutputs.":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; `,i+=`#endif `),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,ee.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(i+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) `,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._directionWName,ee.Vector3)} = normalize(vec3${e.fSuffix}(${this.world.associatedVariableName} * vec4${e.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0))); `:i+=`${t?"vertexOutputs.":""}${this._directionWName} = normalize(vec3${e.fSuffix}(${this.world.associatedVariableName} * vec4${e.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0))); `,i+=`#endif `),i}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} `,e._emitCubeSampler(this._cubeSamplerName,"",!0),e._samplerDeclaration+=`#else `,e._emit2DSampler(this._2DSamplerName,"",!0),e._samplerDeclaration+=`#endif `,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"},{search:/fn computeReflectionCoords\(worldPos: vec4f,worldNormal: vec3f\)->vec3f/g,replace:"fn DUMMYFUNC()"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,ee.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,ee.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i,r=!1,n=!1){i||(i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const o=(e.shaderLanguage===1?"uniforms.":"")+this._reflectionMatrixName,l=`normalize(${this._directionWName})`,c=`${this._positionUVWName}`,u=`${this.cameraPosition.associatedVariableName}`,h=`${this.view.associatedVariableName}`;t+=".xyz";let d=` #ifdef ${this._defineMirroredEquirectangularFixedName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeMirroredFixedEquirectangularCoords(${i}, ${t}, ${l}); #endif #ifdef ${this._defineEquirectangularFixedName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeFixedEquirectangularCoords(${i}, ${t}, ${l}); #endif #ifdef ${this._defineEquirectangularName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeEquirectangularCoords(${i}, ${t}, ${u}.xyz, ${o}); #endif #ifdef ${this._defineSphericalName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeSphericalCoords(${i}, ${t}, ${h}, ${o}); #endif #ifdef ${this._definePlanarName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computePlanarCoords(${i}, ${t}, ${u}.xyz, ${o}); #endif #ifdef ${this._defineCubicName} #ifdef ${this._defineLocalCubicName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeCubicLocalCoords(${i}, ${t}, ${u}.xyz, ${o}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); #else ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeCubicCoords(${i}, ${t}, ${u}.xyz, ${o}); #endif #endif #ifdef ${this._defineProjectionName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeProjectionCoords(${i}, ${h}, ${o}); #endif #ifdef ${this._defineSkyboxName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = computeSkyBoxCoords(${c}, ${o}); #endif #ifdef ${this._defineExplicitName} ${e._declareLocalVar(this._reflectionVectorName,ee.Vector3)} = vec3(0, 0, 0); #endif `;return n||(d+=`#ifdef ${this._defineOppositeZ} ${this._reflectionVectorName}.z *= -1.0; #endif `),r||(d+=` #ifdef ${this._define3DName} ${e._declareLocalVar(this._reflectionCoordsName,ee.Vector3)} = ${this._reflectionVectorName}; #else ${e._declareLocalVar(this._reflectionCoordsName,ee.Vector2)} = ${this._reflectionVectorName}.xy; #ifdef ${this._defineProjectionName} ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; #endif ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; #endif `),d}handleFragmentSideCodeReflectionColor(e,t,i=".rgb"){let r=ee.Vector4;i.length===3&&(r=ee.Vector3);let n=`${e._declareLocalVar(this._reflectionColorName,r)}; #ifdef ${this._define3DName} `;return t?n+=`${this._reflectionColorName} = ${e._generateTextureSampleCubeLOD(this._reflectionVectorName,this._cubeSamplerName,t)}${i}; `:n+=`${this._reflectionColorName} = ${e._generateTextureSampleCube(this._reflectionVectorName,this._cubeSamplerName)}${i}; `,n+=` #else `,t?n+=`${this._reflectionColorName} =${e._generateTextureSampleLOD(this._reflectionCoordsName,this._2DSamplerName,t)}${i}; `:n+=`${this._reflectionColorName} = ${e._generateTextureSample(this._reflectionCoordsName,this._2DSamplerName)}${i}; `,n+=`#endif `,n}writeOutputs(e,t){let i="";if(e.target===be.Fragment)for(const r of this._outputs)r.hasEndpoints&&(i+=`${e._declareOutput(r)} = ${t}.${r.name}; `);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); `}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); `;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ss.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=_a.Parse(e.texture,t,i):this.texture=xe.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}F([Jt("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:lw._OnGenerateOnlyFragmentCodeChanged}})],lw.prototype,"generateOnlyFragmentCode",void 0);ve("BABYLON.ReflectionTextureBaseBlock",lw);class sHe extends lw{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,fe.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,fe.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?be.Fragment:be.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?be.Fragment:be.Vertex}constructor(e){super(e),this.registerInput("position",ee.AutoDetect,!1,be.Vertex),this.registerInput("worldPosition",ee.Vector4,!1,be.Vertex),this.registerInput("worldNormal",ee.Vector4,!1,be.Fragment),this.registerInput("world",ee.Matrix,!1,be.Vertex),this.registerInput("cameraPosition",ee.Vector3,!1,be.Fragment),this.registerInput("view",ee.Matrix,!1,be.Fragment),this.registerOutput("rgb",ee.Color3,be.Fragment),this.registerOutput("rgba",ee.Color4,be.Fragment),this.registerOutput("r",ee.Float,be.Fragment),this.registerOutput("g",ee.Float,be.Fragment),this.registerOutput("b",ee.Float,be.Fragment),this.registerOutput("a",ee.Float,be.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.CameraPosition&&t(r));i||(i=new nr("cameraPosition"),i.setAsSystemValue(mr.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,`vec4${e.fSuffix}(0.)`),this;if(e.target!==be.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`${e._declareLocalVar(t,ee.Vector4)} = normalize(${this.worldNormal.associatedVariableName}); `,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(e,t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(e,void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}ve("BABYLON.ReflectionTextureBlock",sHe);class Zz extends qt{constructor(e){super(e,be.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",ee.AutoDetect,!1,be.VertexAndFragment),this.registerOutput("depth",ee.Float,be.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector2|ee.Vector3|ee.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?be.VertexAndFragment:be.Fragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,t.type===ee.Vector3?ee.Vector3:t.type===ee.Vector4?ee.Vector4:ee.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,ee.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; `,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===be.Fragment)return;const n=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,a=e.shaderLanguage===0?"":", 0";e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)}= ${n} ${i.associatedVariableName}.xy${a}); `;return}const r=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;if(this.uv.ownerBlock.target===be.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${r} ${i.associatedVariableName}.xy); `;return}e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = ${r} ${this._mainUVName}); `}_writeOutput(e,t,i,r=!1){if(r){if(e.target===be.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===be.Fragment){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `;return}e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==be.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(t=>t.isConnectedInFragmentShader)){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}F([Jt("Use non linear depth",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(s,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),s&&s.disableDepthRenderer(),i}}})],Zz.prototype,"useNonLinearDepth",void 0);F([Jt("Store Camera space Z",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(s,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),s&&s.disableDepthRenderer(),i}}})],Zz.prototype,"storeCameraSpaceZ",void 0);F([Jt("Force 32 bits float",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:s=>s==null?void 0:s.disableDepthRenderer()}})],Zz.prototype,"force32itsFloat",void 0);ve("BABYLON.SceneDepthBlock",Zz);class nHe extends qt{constructor(e){super(e,be.VertexAndFragment,!0),this.registerInput("worldPosition",ee.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>Pyt),void 0),Ue(()=>Promise.resolve().then(()=>Iyt),void 0),Ue(()=>Promise.resolve().then(()=>Lyt),void 0),Ue(()=>Promise.resolve().then(()=>Dyt),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>Syt),void 0),Ue(()=>Promise.resolve().then(()=>Cyt),void 0),Ue(()=>Promise.resolve().then(()=>Myt),void 0),Ue(()=>Promise.resolve().then(()=>Tyt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get target(){return be.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const r=e.getScene(),n=!!(t.clipPlane??r.clipPlane),a=!!(t.clipPlane2??r.clipPlane2),o=!!(t.clipPlane3??r.clipPlane3),l=!!(t.clipPlane4??r.clipPlane4),c=!!(t.clipPlane5??r.clipPlane5),u=!!(t.clipPlane6??r.clipPlane6);i.setValue("CLIPPLANE",n,!0),i.setValue("CLIPPLANE2",a,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",l,!0),i.setValue("CLIPPLANE5",c,!0),i.setValue("CLIPPLANE6",u,!0)}bind(e,t,i){if(!i)return;const r=i.getScene();Xa(e,t,r)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==be.Fragment){const i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane",ee.Vector4),e._emitUniformFromString("vClipPlane2",ee.Vector4),e._emitUniformFromString("vClipPlane3",ee.Vector4),e._emitUniformFromString("vClipPlane4",ee.Vector4),e._emitUniformFromString("vClipPlane5",ee.Vector4),e._emitUniformFromString("vClipPlane6",ee.Vector4);return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}ve("BABYLON.ClipPlanesBlock",nHe);class aHe extends qt{get texture(){return null}set texture(e){}constructor(e,t=be.VertexAndFragment){super(e,t,!1),this.registerOutput("position",ee.Object,be.VertexAndFragment,new ra("position",this,1,y0,"ImageSourceBlock")),this.registerOutput("depth",ee.Object,be.VertexAndFragment,new ra("depth",this,1,y0,"ImageSourceBlock")),this.registerOutput("normal",ee.Object,be.VertexAndFragment,new ra("normal",this,1,y0,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==be.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const r=t.getScene().enablePrePassRenderer();if(!r)return;const n=r.defaultRT;n.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,n.textures[r.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,n.textures[r.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,n.textures[r.getIndex(6)]))}}ve("BABYLON.PrePassTextureBlock",aHe);class oHe extends qt{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==be.VertexAndFragment)return t.target;if(e.connectedPoint.target!==be.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,be.Neutral),this._endpoints=[],this.registerInput("input",ee.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)t.indexOf(r)===-1&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name,this._outputs=this._endpoints.map(t=>t.output)}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null,this._outputs=this._endpoints.map(i=>i.output))}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}ve("BABYLON.NodeMaterialTeleportInBlock",oHe);class lHe extends qt{constructor(e){super(e,be.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",ee.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=e._declareOutput(this.output)+` = ${this.entryPoint.input.associatedVariableName}; `)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&t.indexOf(this.entryPoint)===-1&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); `),e}serialize(){var t;const e=super.serialize();return e.entryPoint=((t=this.entryPoint)==null?void 0:t.uniqueId)??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}ve("BABYLON.NodeMaterialTeleportOutBlock",lHe);class cHe extends mee{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; `,this}}ve("BABYLON.AddBlock",cHe);class uHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("input",ee.AutoDetect),this.registerInput("factor",ee.Float),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; `,this}}ve("BABYLON.ScaleBlock",uHe);class Mee extends qt{constructor(e){super(e,be.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===1?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)})); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; `;return e+=`${this._codeVariableName}.maximum = ${this.maximum}; `,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}F([Jt("Minimum",1)],Mee.prototype,"minimum",void 0);F([Jt("Maximum",1)],Mee.prototype,"maximum",void 0);ve("BABYLON.ClampBlock",Mee);class hHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("left",ee.AutoDetect),this.registerInput("right",ee.AutoDetect),this.registerOutput("output",ee.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ee.Float),this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ee.Vector2),this._inputs[1].excludedConnectionPointTypes.push(ee.Float),this._inputs[1].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ee.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); `,this}}ve("BABYLON.CrossBlock",hHe);class dHe extends qt{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(n=>{const a=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),o=e._getGLType(n.type);t=t.replace(a,o),i=i.replace(a,o)}),this._outputs.forEach(n=>{const a=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),o=e._getGLType(n.type);t=t.replace(a,o),i=i.replace(a,o)}),e._emitFunction(i,t,""),this._outputs.forEach(n=>{e.compilationString+=e._declareOutput(n)+`; `}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((n,a)=>{var o,l;a>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(n.name)!==-1?e.compilationString+=((l=(o=n.connectedPoint)==null?void 0:o.ownerBlock)==null?void 0:l.samplerName)??n.associatedVariableName:e.compilationString+=n.associatedVariableName,r=!0}),this._outputs.forEach((n,a)=>{(a>0||r)&&(e.compilationString+=", "),e.compilationString+=n.associatedVariableName}),e.compilationString+=`); `,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; `,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,r;this._options=e,this._code=e.code.join(` `)+` `,this.name=this.name||e.name,this.target=be[e.target],(t=e.inParameters)==null||t.forEach((n,a)=>{const o=ee[n.type];n.type==="sampler2D"||n.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(n.name),this.registerInput(n.name,ee.Object,!0,be.VertexAndFragment,new ra(n.name,this,0,y0,"ImageSourceBlock"))):this.registerInput(n.name,o),Object.defineProperty(this,n.name,{get:function(){return this._inputs[a]},enumerable:!0,configurable:!0})}),(i=e.outParameters)==null||i.forEach((n,a)=>{this.registerOutput(n.name,ee[n.type]),Object.defineProperty(this,n.name,{get:function(){return this._outputs[a]},enumerable:!0,configurable:!0}),n.type==="BasedOnInput"&&(this._outputs[a]._typeConnectionSource=this._findInputByName(n.typeFromInput)[0])}),(r=e.inLinkedConnectionTypes)==null||r.forEach(n=>{this._linkConnectionTypes(this._findInputByName(n.input1)[1],this._findInputByName(n.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.CameraPosition&&t(r));i||(i=new nr("cameraPosition"),i.setAsSystemValue(mr.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); `,this}}ve("BABYLON.ViewDirectionBlock",r_e);const hTt="fresnelFunction",dTt=`#ifdef FRESNEL float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) {float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} #endif `;de.IncludesShadersStore[hTt]=dTt;class AHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("worldNormal",ee.Vector4),this.registerInput("viewDirection",ee.Vector3),this.registerInput("bias",ee.Float),this.registerInput("power",ee.Float),this.registerOutput("fresnel",ee.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new r_e("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new nr("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new nr("power");t.value=1,t.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=e._declareOutput(this.fresnel)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName}); `,this}}ve("BABYLON.FresnelBlock",AHe);class bHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("left",ee.AutoDetect),this.registerInput("right",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); `,this}}ve("BABYLON.MaxBlock",bHe);class CHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("left",ee.AutoDetect),this.registerInput("right",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); `,this}}ve("BABYLON.MinBlock",CHe);class SHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("left",ee.AutoDetect),this.registerInput("right",ee.AutoDetect),this.registerOutput("output",ee.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ee.Float),this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ee.Float),this._inputs[1].excludedConnectionPointTypes.push(ee.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); `,this}}ve("BABYLON.DistanceBlock",SHe);class EHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("value",ee.AutoDetect),this.registerOutput("output",ee.Float),this._inputs[0].excludedConnectionPointTypes.push(ee.Float),this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.value.associatedVariableName}); `,this}}ve("BABYLON.LengthBlock",EHe);class THe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("value",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = -1.0 * ${this.value.associatedVariableName}; `,this}}ve("BABYLON.NegateBlock",THe);class MHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("value",ee.AutoDetect),this.registerInput("power",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); `,this}}ve("BABYLON.PowBlock",MHe);class RHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("seed",ee.AutoDetect),this.registerOutput("output",ee.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector2|ee.Vector3|ee.Vector4|ee.Color3|ee.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=e._declareOutput(t)+` = getRand(${this.seed.associatedVariableName}.xy); `,this}}ve("BABYLON.RandomNumberBlock",RHe);class IHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("x",ee.Float),this.registerInput("y",ee.Float),this.registerOutput("output",ee.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===1?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); `,this}}ve("BABYLON.ArcTan2Block",IHe);class PHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("value",ee.AutoDetect),this.registerInput("edge0",ee.Float),this.registerInput("edge1",ee.Float),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(this.value.type);return e.compilationString+=e._declareOutput(t)+` = smoothstep(${i}(${this.edge0.associatedVariableName}), ${i}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName}); `,this}}ve("BABYLON.SmoothStepBlock",PHe);class wHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("input",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===ee.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName}); `:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName}; `,this}}ve("BABYLON.ReciprocalBlock",wHe);class DHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("value",ee.AutoDetect),this.registerInput("reference",ee.AutoDetect),this.registerInput("distance",ee.Float),this.registerInput("replacement",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(ee.Float),this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ee.Float),this._inputs[1].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[3].excludedConnectionPointTypes.push(ee.Float),this._inputs[3].excludedConnectionPointTypes.push(ee.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+`; `,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { `,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; `,e.compilationString+=`} else { `,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; `,e.compilationString+=`} `,this}}ve("BABYLON.ReplaceColorBlock",DHe);class LHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("value",ee.AutoDetect),this.registerInput("steps",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(ee.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName}); `,this}}ve("BABYLON.PosterizeBlock",LHe);var sde;(function(s){s[s.SawTooth=0]="SawTooth",s[s.Square=1]="Square",s[s.Triangle=2]="Triangle"})(sde||(sde={}));class OHe extends qt{constructor(e){super(e,be.Neutral),this.kind=0,this.registerInput("input",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case 0:{e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); `;break}case 1:{e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); `;break}case 2:{e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; `;break}}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}ve("BABYLON.WaveBlock",OHe);class QQ{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class NHe extends qt{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,be.Neutral),this.colorSteps=[new QQ(0,Re.Black()),new QQ(1,Re.White())],this.onValueChangedObservable=new Ae,this.registerInput("gradient",ee.AutoDetect),this.registerOutput("output",ee.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Float|ee.Vector2|ee.Vector3|ee.Vector4|ee.Color3|ee.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e,t){const i=this.colorSteps[e];return`${t}(${i.color.r}, ${i.color.g}, ${i.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(ee.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.); `;return}const r=e._getFreeVariableName("gradientTempColor"),n=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(r,ee.Vector3)} = ${this._writeColorConstant(0,i)}; `,e.compilationString+=`${e._declareLocalVar(n,ee.Float)}; `;let a=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==ee.Float&&(a+=".x");for(let o=1;o= d11.y) { vec2 temp = d11.yx; d11.x = temp.x; d11.y = temp.y; } `,t+=` if (d11.x >= d11.z) { vec2 temp = d11.zx; d11.x = temp.x; d11.z = temp.y; } `,t+=` d12 = min(d12, d21); // 2nd smallest now not in d21 `,t+=` d12 = min(d12, d22); // nor in d22 `,t+=` d12 = min(d12, d31); // nor in d31 `,t+=` d12 = min(d12, d32); // nor in d32 `,t+=` vec2 temp2 = min(d11.yz, d12.xy); // nor in d12.yz `,t+=` d11.y = temp2.x; `,t+=` d11.z = temp2.y; `,t+=` d11.y = min(d11.y, d12.z); // Only two more to go `,t+=` d11.y = min(d11.y, d11.z); // Done! (Phew!) `,t+=` return sqrt(d11.xy); // F1, F2 `,t+=`} `,e.shaderLanguage===1?t=e._babylonSLtoWGSL(t):t=e._babylonSLtoGLSL(t),e._emitFunction("worley3D",t,"// Worley3D");const i=e._getFreeVariableName("worleyTemp");return e.compilationString+=`${e._declareLocalVar(i,ee.Vector2)} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance}); `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${i}; `),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${i}.x; `),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${i}.y; `),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance}; `}serialize(){const e=super.serialize();return e.manhattanDistance=this.manhattanDistance,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.manhattanDistance=e.manhattanDistance}}F([Jt("Use Manhattan Distance",0,"PROPERTIES",{notifiers:{update:!1}})],s_e.prototype,"manhattanDistance",void 0);ve("BABYLON.WorleyNoise3DBlock",s_e);class BHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("seed",ee.Vector3),this.registerOutput("output",ee.Float)}getClassName(){return"SimplexPerlin3DBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let t=`const float SKEWFACTOR = 1.0/3.0; `;return t+=`const float UNSKEWFACTOR = 1.0/6.0; `,t+=`const float SIMPLEX_CORNER_POS = 0.5; `,t+=`const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485; `,t+=`float SimplexPerlin3D( vec3 source ){ `,t+=` vec3 P = source; `,t+=` P.x = [P.x == 0. && P.y == 0. && P.z == 0. ? 0.00001 : P.x]; `,t+=` P *= SIMPLEX_TETRAHADRON_HEIGHT; `,t+=" vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );",t+=` vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) ); `,t+=` vec3 g = step(x0.yzx, x0.xyz); `,t+=` vec3 l = 1.0 - g; `,t+=` vec3 Pi_1 = min( g.xyz, l.zxy ); `,t+=` vec3 Pi_2 = max( g.xyz, l.zxy ); `,t+=` vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR; `,t+=` vec3 x2 = x0 - Pi_2 + SKEWFACTOR; `,t+=` vec3 x3 = x0 - SIMPLEX_CORNER_POS; `,t+=` vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x ); `,t+=` vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y ); `,t+=` vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z ); `,t+=` Pi = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0; `,t+=` vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 ); `,t+=` vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy; `,t+=` Pt *= Pt; `,t+=` vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) ); `,t+=` Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w ); `,t+=` const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 ); `,t+=` const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 ); `,t+=` vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) ); `,t+=` vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) ); `,t+=` Pi_1 = [( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods]; `,t+=` Pi_2 = [( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods]; `,t+=` vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999; `,t+=` vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999; `,t+=` vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999; `,t+=` vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z ); `,t+=` const float FINAL_NORMALIZATION = 37.837227241611314102871574478976; `,t+=` vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z; `,t+=` kernel_weights = max(0.5 - kernel_weights, vec4(0.)); `,t+=` kernel_weights = kernel_weights*kernel_weights*kernel_weights; `,t+=` return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION; `,t+=`} `,e.shaderLanguage===1?t=e._babylonSLtoWGSL(t):t=e._babylonSLtoGLSL(t),e._emitFunction("SimplexPerlin3D",t,"// SimplexPerlin3D"),e.compilationString+=e._declareOutput(this._outputs[0])+` = SimplexPerlin3D(${this.seed.associatedVariableName}); `,this}}ve("BABYLON.SimplexPerlin3DBlock",BHe);class kHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("normalMap0",ee.AutoDetect),this.registerInput("normalMap1",ee.AutoDetect),this.registerOutput("output",ee.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Color4|ee.Vector3|ee.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Color4|ee.Vector3|ee.Vector4)}getClassName(){return"NormalBlendBlock"}get normalMap0(){return this._inputs[0]}get normalMap1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0],r=this._inputs[1],n=e._getFreeVariableName("stepR"),a=e._getFreeVariableName("stepG");return e.compilationString+=`${e._declareLocalVar(n,ee.Float)} = step(0.5, ${i.associatedVariableName}.r); `,e.compilationString+=`${e._declareLocalVar(a,ee.Float)} = step(0.5, ${i.associatedVariableName}.g); `,e.compilationString+=e._declareOutput(t)+`; `,e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${n}) * ${i.associatedVariableName}.r * ${r.associatedVariableName}.r * 2.0 + ${n} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${r.associatedVariableName}.r) * 2.0); `,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${a}) * ${i.associatedVariableName}.g * ${r.associatedVariableName}.g * 2.0 + ${a} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${r.associatedVariableName}.g) * 2.0); `,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${r.associatedVariableName}.b; `,this}}ve("BABYLON.NormalBlendBlock",kHe);class UHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("input",ee.Vector2),this.registerInput("angle",ee.Float),this.registerOutput("output",ee.Vector2)}getClassName(){return"Rotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new nr("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.angle,r=this.input;return e.compilationString+=e._declareOutput(t)+` = vec2(cos(${i.associatedVariableName}) * ${r.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${r.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${r.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${r.associatedVariableName}.y); `,this}}ve("BABYLON.Rotate2dBlock",UHe);class zHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("incident",ee.AutoDetect),this.registerInput("normal",ee.AutoDetect),this.registerOutput("output",ee.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4|ee.Color3|ee.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4|ee.Color3|ee.Color4)}getClassName(){return"ReflectBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz); `,this}}ve("BABYLON.ReflectBlock",zHe);class VHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("incident",ee.AutoDetect),this.registerInput("normal",ee.AutoDetect),this.registerInput("ior",ee.Float),this.registerOutput("output",ee.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4|ee.Color3|ee.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ee.Vector3|ee.Vector4|ee.Color3|ee.Color4)}getClassName(){return"RefractBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get ior(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName}); `,this}}ve("BABYLON.RefractBlock",VHe);class GHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("color",ee.Color3),this.registerInput("level",ee.Float),this.registerOutput("output",ee.Color3)}getClassName(){return"DesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],r=this.color.associatedVariableName,n=e._getFreeVariableName("colorMin"),a=e._getFreeVariableName("colorMax"),o=e._getFreeVariableName("colorMerge");return e.compilationString+=`${e._declareLocalVar(n,ee.Float)} = min(min(${r}.x, ${r}.y), ${r}.z); `,e.compilationString+=`${e._declareLocalVar(a,ee.Float)} = max(max(${r}.x, ${r}.y), ${r}.z); `,e.compilationString+=`${e._declareLocalVar(o,ee.Float)} = 0.5 * (${n} + ${a}); `,e.compilationString+=e._declareOutput(t)+` = mix(${r}, ${e._getShaderType(ee.Vector3)}(${o}, ${o}, ${o}), ${this.level.associatedVariableName}); `,this}}ve("BABYLON.DesaturateBlock",GHe);class hT extends qt{constructor(e){super(e,be.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",ee.Float,!0,be.Fragment),this.registerInput("color",ee.Color3,!0,be.Fragment),this.registerInput("roughness",ee.Float,!0,be.Fragment),this.registerOutput("sheen",ee.Object,be.Fragment,new ra("sheen",this,1,hT,"SheenBlock"))}initialize(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")}getClassName(){return"SheenBlock"}get intensity(){return this._inputs[0]}get color(){return this._inputs[1]}get roughness(){return this._inputs[2]}get sheen(){return this._outputs[0]}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("SHEEN",!0),i.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),i.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),i.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)}getCode(e,t){let i="";const r=this.color.isConnected?this.color.associatedVariableName:`vec3${t.fSuffix}(1.)`,n=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",a=this.roughness.isConnected?this.roughness.associatedVariableName:"0.",o=`vec4${t.fSuffix}(0.)`,l=t.shaderLanguage===1;return i=`#ifdef SHEEN ${l?"var sheenOut: sheenOutParams":"sheenOutParams sheenOut"}; ${t._declareLocalVar("vSheenColor",ee.Vector4)} = vec4${t.fSuffix}(${r}, ${n}); sheenOut = sheenBlock( vSheenColor #ifdef SHEEN_ROUGHNESS , ${a} #endif , roughness #ifdef SHEEN_TEXTURE , ${o} ${l?`, ${o}Sampler`:""} , 1.0 #endif , reflectance #ifdef SHEEN_LINKWITHALBEDO , baseColor , surfaceAlbedo #endif #ifdef ENVIRONMENTBRDF , NdotV , environmentBrdf #endif #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) , AARoughnessFactors , ${l?"uniforms.":""}${e==null?void 0:e._vReflectionMicrosurfaceInfosName} , ${e==null?void 0:e._vReflectionInfosName} , ${e==null?void 0:e.reflectionColor} , ${l?"uniforms.":""}vLightingIntensity #ifdef ${e==null?void 0:e._define3DName} , ${e==null?void 0:e._cubeSamplerName} ${l?`, ${e==null?void 0:e._cubeSamplerName}Sampler`:""} #else , ${e==null?void 0:e._2DSamplerName} ${l?`, ${e==null?void 0:e._2DSamplerName}Sampler`:""} #endif , reflectionOut.reflectionCoords , NdotVUnclamped #ifndef LODBASEDMICROSFURACE #ifdef ${e==null?void 0:e._define3DName} , ${e==null?void 0:e._cubeSamplerName} ${l?`, ${e==null?void 0:e._cubeSamplerName}Sampler`:""} , ${e==null?void 0:e._cubeSamplerName} ${l?`, ${e==null?void 0:e._cubeSamplerName}Sampler`:""} #else , ${e==null?void 0:e._2DSamplerName} ${l?`, ${e==null?void 0:e._2DSamplerName}Sampler`:""} , ${e==null?void 0:e._2DSamplerName} ${l?`, ${e==null?void 0:e._2DSamplerName}Sampler`:""} #endif #endif #if !defined(${e==null?void 0:e._defineSkyboxName}) && defined(RADIANCEOCCLUSION) , seo #endif #if !defined(${e==null?void 0:e._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${e==null?void 0:e._define3DName}) , eho #endif #endif ); #ifdef SHEEN_LINKWITHALBEDO surfaceAlbedo = sheenOut.surfaceAlbedo; #endif #endif `,i}_buildBlock(e){return e.target===be.Fragment&&e.sharedData.blocksWithDefines.push(this),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.albedoScaling = ${this.albedoScaling}; `,e+=`${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo}; `,e}serialize(){const e=super.serialize();return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo}}F([Jt("Albedo scaling",0,"PROPERTIES",{notifiers:{update:!0}})],hT.prototype,"albedoScaling",void 0);F([Jt("Link sheen with albedo",0,"PROPERTIES",{notifiers:{update:!0}})],hT.prototype,"linkSheenWithAlbedo",void 0);ve("BABYLON.SheenBlock",hT);class qz extends qt{constructor(e){super(e,be.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",ee.Float,!0,be.Fragment),this.registerInput("direction",ee.Vector2,!0,be.Fragment),this.registerInput("uv",ee.Vector2,!0),this.registerInput("worldTangent",ee.Vector4,!0),this.registerInput("TBN",ee.Object,!0,be.VertexAndFragment,new ra("TBN",this,0,uT,"TBNBlock")),this.registerInput("roughness",ee.Float,!0,be.Fragment),this.registerOutput("anisotropy",ee.Object,be.Fragment,new ra("anisotropy",this,1,qz,"AnisotropyBlock"))}initialize(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")}getClassName(){return"AnisotropyBlock"}get intensity(){return this._inputs[0]}get direction(){return this._inputs[1]}get uv(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get TBN(){return this._inputs[4]}get roughness(){return this._inputs[5]}get anisotropy(){return this._outputs[0]}_generateTBNSpace(e){let t="";const i=`//${this.name}`,r=this.uv,n=this.worldPositionConnectionPoint,a=this.worldNormalConnectionPoint,o=this.worldTangent,l=e.shaderLanguage===1;r.isConnected||fe.Error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const c={search:/defined\(TANGENT\)/g,replace:o.isConnected?"defined(TANGENT)":"defined(IGNORE)"},u=this.TBN;return u.isConnected?e.compilationString+=` #ifdef TBNBLOCK ${l?"var TBN":"mat3 TBN"} = ${u.associatedVariableName}; #endif `:o.isConnected&&(t+=`${e._declareLocalVar("tbnNormal",ee.Vector3)} = normalize(${a.associatedVariableName}.xyz); `,t+=`${e._declareLocalVar("tbnTangent",ee.Vector3)} = normalize(${o.associatedVariableName}.xyz); `,t+=`${e._declareLocalVar("tbnBitangent",ee.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; `,t+=`${l?"var vTBN":"mat3 vTBN"} = ${l?"mat3x3f":"mat3"}(tbnTangent, tbnBitangent, tbnNormal); `),t+=` #if defined(${o.isConnected?"TANGENT":"IGNORE"}) && defined(NORMAL) ${l?"var TBN":"mat3 TBN"} = vTBN; #else ${l?"var TBN":"mat3 TBN"} = cotangent_frame(${a.associatedVariableName+".xyz"}, ${"v_"+n.associatedVariableName+".xyz"}, ${r.isConnected?r.associatedVariableName:"vec2(0.)"}, vec2${e.fSuffix}(1., 1.)); #endif `,e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[c]}),t}getCode(e,t=!1){let i="";t&&(i+=this._generateTBNSpace(e));const r=e.shaderLanguage===1,n=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",a=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)",o=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return i+=`${r?"var anisotropicOut: anisotropicOutParams":"anisotropicOutParams anisotropicOut"}; anisotropicOut = anisotropicBlock( vec3(${a}, ${n}), ${o}, #ifdef ANISOTROPIC_TEXTURE vec3(0.), #endif TBN, normalW, viewDirectionW ); `,i}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("ANISOTROPIC",!0),i.setValue("ANISOTROPIC_TEXTURE",!1,!0),i.setValue("ANISOTROPIC_LEGACY",!this.roughness.isConnected)}bind(e,t,i){super.bind(e,t,i),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_buildBlock(e){return e.target===be.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,ee.Float)),this}}ve("BABYLON.AnisotropyBlock",qz);class dT extends lw{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,fe.Error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?be.Fragment:be.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",ee.AutoDetect,!1,be.Vertex),this.registerInput("world",ee.Matrix,!1,be.Vertex),this.registerInput("color",ee.Color3,!0,be.Fragment),this.registerOutput("reflection",ee.Object,be.Fragment,new ra("reflection",this,1,dT,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this._getTexture(),n=r&&r.getTextureMatrix;i.setValue("REFLECTION",n,!0),n&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==xe.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);const n=this._getTexture();if(!n||!r)return;n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n);const a=n.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,a,n.lodGenerationScale,n.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,a,At.Log2(a));const o=r.materialDefines,l=n.sphericalPolynomial;if(o.USESPHERICALFROMREFLECTIONMAP&&l)if(o.SPHERICAL_HARMONICS){const c=l.preScaledHarmonics;e.setVector3("vSphericalL00",c.l00),e.setVector3("vSphericalL1_1",c.l1_1),e.setVector3("vSphericalL10",c.l10),e.setVector3("vSphericalL11",c.l11),e.setVector3("vSphericalL2_2",c.l2_2),e.setVector3("vSphericalL2_1",c.l2_1),e.setVector3("vSphericalL20",c.l20),e.setVector3("vSphericalL21",c.l21),e.setVector3("vSphericalL22",c.l22)}else e.setFloat3("vSphericalX",l.x.x,l.x.y,l.x.z),e.setFloat3("vSphericalY",l.y.x,l.y.y,l.y.z),e.setFloat3("vSphericalZ",l.z.x,l.z.y,l.z.z),e.setFloat3("vSphericalXX_ZZ",l.xx.x-l.zz.x,l.xx.y-l.zz.y,l.xx.z-l.zz.z),e.setFloat3("vSphericalYY_ZZ",l.yy.x-l.zz.x,l.yy.y-l.zz.y,l.yy.z-l.zz.z),e.setFloat3("vSphericalZZ",l.zz.x,l.zz.y,l.zz.z),e.setFloat3("vSphericalXY",l.xy.x,l.xy.y,l.xy.z),e.setFloat3("vSphericalYZ",l.yz.x,l.yz.y,l.yz.z),e.setFloat3("vSphericalZX",l.zx.x,l.zx.y,l.zx.z)}handleVertexSide(e){let t=super.handleVertexSide(e);const i=e.shaderLanguage===1;e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});const r=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,ee.Vector3,"defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22",ee.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ",ee.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX",ee.Vector3,"SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) ${e._declareLocalVar(r,ee.Vector3)} = (${(i?"uniforms.":"")+this._reflectionMatrixName} * vec4${e.fSuffix}(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; #ifdef ${this._defineOppositeZ} ${r}.z *= -1.0; #endif ${i?"vertexOutputs.":""}${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${r}); #endif `,t}getCode(e,t){let i="";this.handleFragmentSideInits(e);const r=e.shaderLanguage===1;e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),r||(e._emitFunction("sampleReflection",` #ifdef ${this._define3DName} #define sampleReflection(s, c) textureCube(s, c) #else #define sampleReflection(s, c) texture2D(s, c) #endif `,`//${this.name}`),e._emitFunction("sampleReflectionLod",` #ifdef ${this._define3DName} #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) #else #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) #endif `,`//${this.name}`));const n=r?` fn computeReflectionCoordsPBR(worldPos: vec4f, worldNormal: vec3f) -> vec3f { ${this.handleFragmentSideCodeReflectionCoords(e,"worldNormal","worldPos",!0,!0)} return ${this._reflectionVectorName}; } `:` vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { ${this.handleFragmentSideCodeReflectionCoords(e,"worldNormal","worldPos",!0,!0)} return ${this._reflectionVectorName}; } `;return e._emitFunction("computeReflectionCoordsPBR",n,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,ee.Vector3),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,ee.Vector2),i+=`#ifdef REFLECTION ${e._declareLocalVar(this._vReflectionInfosName,ee.Vector2)} = vec2${e.fSuffix}(1., 0.); ${r?"var reflectionOut: reflectionOutParams":"reflectionOutParams reflectionOut"}; reflectionOut = reflectionBlock( ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:(r?"input.":"")+"v_"+this.worldPosition.associatedVariableName}.xyz , ${t} , alphaG , ${(r?"uniforms.":"")+this._vReflectionMicrosurfaceInfosName} , ${this._vReflectionInfosName} , ${this.reflectionColor} #ifdef ANISOTROPIC ,anisotropicOut #endif #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) ,NdotVUnclamped #endif #ifdef ${this._defineLinearSpecularReflection} , roughness #endif #ifdef ${this._define3DName} , ${this._cubeSamplerName} ${r?`, ${this._cubeSamplerName}Sampler`:""} #else , ${this._2DSamplerName} ${r?`, ${this._2DSamplerName}Sampler`:""} #endif #if defined(NORMAL) && defined(USESPHERICALINVERTEX) , ${r?"input.":""}${this._vEnvironmentIrradianceName} #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) , ${this._reflectionMatrixName} #endif #endif #ifdef USEIRRADIANCEMAP , irradianceSampler // ** not handled ** ${r?", irradianceSamplerSampler":""} #endif #ifndef LODBASEDMICROSFURACE #ifdef ${this._define3DName} , ${this._cubeSamplerName} ${r?`, ${this._cubeSamplerName}Sampler`:""} , ${this._cubeSamplerName} ${r?`, ${this._cubeSamplerName}Sampler`:""} #else , ${this._2DSamplerName} ${r?`, ${this._2DSamplerName}Sampler`:""} , ${this._2DSamplerName} ${r?`, ${this._2DSamplerName}Sampler`:""} #endif #endif #ifdef REALTIME_FILTERING , ${this._vReflectionFilteringInfoName} #endif ); #endif `,i}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==be.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; `),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; `,e+=`${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; `,e}serialize(){var t;const e=super.serialize();return e.useSphericalHarmonics=this.useSphericalHarmonics,e.forceIrradianceInFragment=this.forceIrradianceInFragment,e.gammaSpace=((t=this.texture)==null?void 0:t.gammaSpace)??!0,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}F([Jt("Spherical Harmonics",0,"ADVANCED",{notifiers:{update:!0}})],dT.prototype,"useSphericalHarmonics",void 0);F([Jt("Force irradiance in fragment",0,"ADVANCED",{notifiers:{update:!0}})],dT.prototype,"forceIrradianceInFragment",void 0);ve("BABYLON.ReflectionBlock",dT);class l6 extends qt{constructor(e){super(e,be.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",ee.Float,!1,be.Fragment),this.registerInput("roughness",ee.Float,!0,be.Fragment),this.registerInput("indexOfRefraction",ee.Float,!0,be.Fragment),this.registerInput("normalMapColor",ee.Color3,!0,be.Fragment),this.registerInput("uv",ee.Vector2,!0,be.Fragment),this.registerInput("tintColor",ee.Color3,!0,be.Fragment),this.registerInput("tintAtDistance",ee.Float,!0,be.Fragment),this.registerInput("tintThickness",ee.Float,!0,be.Fragment),this.registerInput("worldTangent",ee.Vector4,!0),this.registerInput("worldNormal",ee.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ee.Color4|ee.Vector4|ee.Vector3),this.registerInput("TBN",ee.Object,!0,be.VertexAndFragment,new ra("TBN",this,0,uT,"TBNBlock")),this.registerOutput("clearcoat",ee.Object,be.Fragment,new ra("clearcoat",this,1,l6,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new nr("ClearCoat intensity",be.Fragment,ee.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",this.indexOfRefraction.isConnected?this.indexOfRefraction.connectInputBlock.value===Xo._DefaultIndexOfRefraction:!0,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var h;super.bind(e,t,i);const r=((h=this.indexOfRefraction.connectInputBlock)==null?void 0:h.value)??Xo._DefaultIndexOfRefraction,n=1-r,a=1+r,o=Math.pow(-n/a,2),l=1/r;e.setFloat4("vClearCoatRefractionParams",o,l,n,a);const c=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,u=c!=null&&c.perturbedNormal.isConnected?c.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",u!=null&&u.invertX?1:-1,u!=null&&u.invertY?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",u!=null&&u.invertX?-1:1,u!=null&&u.invertY?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_generateTBNSpace(e,t,i){let r="";const n=`//${this.name}`,a=this.worldTangent,o=e.shaderLanguage===1;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const l={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},c=this.TBN;return c.isConnected?e.compilationString+=` #ifdef TBNBLOCK ${o?"var TBN":"mat3 TBN"} = ${c.associatedVariableName}; #endif `:a.isConnected&&(r+=`${e._declareLocalVar("tbnNormal",ee.Vector3)} = normalize(${i}.xyz); `,r+=`${e._declareLocalVar("tbnTangent",ee.Vector3)} = normalize(${a.associatedVariableName}.xyz); `,r+=`${e._declareLocalVar("tbnBitangent",ee.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; `,r+=`${o?"var vTBN":"mat3 vTBN"} = ${o?"mat3x3f":"mat3"}(tbnTangent, tbnBitangent, tbnNormal); `),e._emitFunctionFromInclude("bumpFragmentMainFunctions",n,{replaceStrings:[l]}),r}static GetCode(e,t,i,r,n,a,o){let l="";const c=t!=null&&t.intensity.isConnected?t.intensity.associatedVariableName:"1.",u=t!=null&&t.roughness.isConnected?t.roughness.associatedVariableName:"0.",h=t!=null&&t.normalMapColor.isConnected?t.normalMapColor.associatedVariableName:`vec3${e.fSuffix}(0.)`,d=t!=null&&t.uv.isConnected?t.uv.associatedVariableName:`vec2${e.fSuffix}(0.)`,f=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:`vec3${e.fSuffix}(1.)`,p=t!=null&&t.tintThickness.isConnected?t.tintThickness.associatedVariableName:"1.",m=t!=null&&t.tintAtDistance.isConnected?t.tintAtDistance.associatedVariableName:"1.",g=`vec4${e.fSuffix}(0.)`;if(t){e._emitUniformFromString("vClearCoatRefractionParams",ee.Vector4),e._emitUniformFromString("vClearCoatTangentSpaceParams",ee.Vector2);const y=t.worldNormal;l+=`${e._declareLocalVar("vGeometricNormaClearCoatW",ee.Vector3)} = ${y.isConnected?"normalize("+y.associatedVariableName+".xyz)":"geometricNormalW"}; `}else l+=`${e._declareLocalVar("vGeometricNormaClearCoatW",ee.Vector3)} = geometricNormalW; `;n&&t&&(l+=t._generateTBNSpace(e,r,o),a=t.worldTangent.isConnected);const _=e.shaderLanguage===1;return l+=`${_?"var clearcoatOut: clearcoatOutParams":"clearcoatOutParams clearcoatOut"}; #ifdef CLEARCOAT ${e._declareLocalVar("vClearCoatParams",ee.Vector2)} = vec2${e.fSuffix}(${c}, ${u}); ${e._declareLocalVar("vClearCoatTintParams",ee.Vector4)} = vec4${e.fSuffix}(${f}, ${p}); clearcoatOut = clearcoatBlock( ${r}.xyz , vGeometricNormaClearCoatW , viewDirectionW , vClearCoatParams , specularEnvironmentR0 #ifdef CLEARCOAT_TEXTURE , vec2${e.fSuffix}(0.) #endif #ifdef CLEARCOAT_TINT , vClearCoatTintParams , ${m} , ${_?"uniforms.":""}vClearCoatRefractionParams #ifdef CLEARCOAT_TINT_TEXTURE , ${g} #endif #endif #ifdef CLEARCOAT_BUMP , vec2${e.fSuffix}(0., 1.) , vec4${e.fSuffix}(${h}, 0.) , ${d} #if defined(${a?"TANGENT":"IGNORE"}) && defined(NORMAL) , vTBN #else , ${_?"uniforms.":""}vClearCoatTangentSpaceParams #endif #ifdef OBJECTSPACE_NORMALMAP , normalMatrix #endif #endif #if defined(FORCENORMALFORWARD) && defined(NORMAL) , faceNormal #endif #ifdef REFLECTION , ${_?"uniforms.":""}${i==null?void 0:i._vReflectionMicrosurfaceInfosName} , ${i==null?void 0:i._vReflectionInfosName} , ${i==null?void 0:i.reflectionColor} , ${_?"uniforms.":""}vLightingIntensity #ifdef ${i==null?void 0:i._define3DName} , ${i==null?void 0:i._cubeSamplerName} ${_?`, ${i==null?void 0:i._cubeSamplerName}Sampler`:""} #else , ${i==null?void 0:i._2DSamplerName} ${_?`, ${i==null?void 0:i._2DSamplerName}Sampler`:""} #endif #ifndef LODBASEDMICROSFURACE #ifdef ${i==null?void 0:i._define3DName} , ${i==null?void 0:i._cubeSamplerName} ${_?`, ${i==null?void 0:i._cubeSamplerName}Sampler`:""} , ${i==null?void 0:i._cubeSamplerName} ${_?`, ${i==null?void 0:i._cubeSamplerName}Sampler`:""} #else , ${i==null?void 0:i._2DSamplerName} ${_?`, ${i==null?void 0:i._2DSamplerName}Sampler`:""} , ${i==null?void 0:i._2DSamplerName} ${_?`, ${i==null?void 0:i._2DSamplerName}Sampler`:""} #endif #endif #endif #if defined(ENVIRONMENTBRDF) && !defined(${i==null?void 0:i._defineSkyboxName}) #ifdef RADIANCEOCCLUSION , ambientMonochrome #endif #endif #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) , (${e._generateTernary("1.","-1.",_?"fragmentInputs.frontFacing":"gl_FrontFacing")}) #endif ); #else clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; #endif `,l}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===be.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,ee.Float)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; `,e}serialize(){const e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.remapF0OnInterfaceChange=e.remapF0OnInterfaceChange??!0}}F([Jt("Remap F0 on interface change",0,"ADVANCED")],l6.prototype,"remapF0OnInterfaceChange",void 0);ve("BABYLON.ClearCoatBlock",l6);class Xk extends qt{constructor(e){super(e,be.Fragment),this._isUnique=!0,this.registerInput("intensity",ee.Float,!0,be.Fragment),this.registerInput("indexOfRefraction",ee.Float,!0,be.Fragment),this.registerInput("thickness",ee.Float,!0,be.Fragment),this.registerOutput("iridescence",ee.Object,be.Fragment,new ra("iridescence",this,1,Xk,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new nr("Iridescence intensity",be.Fragment,ee.Float);e.value=1,e.output.connectTo(this.intensity);const t=new nr("Iridescence ior",be.Fragment,ee.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);const i=new nr("Iridescence thickness",be.Fragment,ee.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e,t){let i="";const r=e!=null&&e.intensity.isConnected?e.intensity.associatedVariableName:"1.",n=e!=null&&e.indexOfRefraction.isConnected?e.indexOfRefraction.associatedVariableName:Uc._DefaultIndexOfRefraction,a=e!=null&&e.thickness.isConnected?e.thickness.associatedVariableName:Uc._DefaultMaximumThickness,o=t.shaderLanguage===1;return i+=`${o?"var iridescenceOut: iridescenceOutParams":"iridescenceOutParams iridescenceOut"}; #ifdef IRIDESCENCE iridescenceOut = iridescenceBlock( vec4(${r}, ${n}, 1., ${a}) , NdotV , specularEnvironmentR0 #ifdef CLEARCOAT , NdotVUnclamped #endif ); float iridescenceIntensity = iridescenceOut.iridescenceIntensity; specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; #endif `,i}_buildBlock(e){return e.target===be.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){return super.serialize()}_deserialize(e,t,i){super._deserialize(e,t,i)}}ve("BABYLON.IridescenceBlock",Xk);class Kx extends qt{constructor(e){super(e,be.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",ee.Float,!1,be.Fragment),this.registerInput("tintAtDistance",ee.Float,!0,be.Fragment),this.registerInput("volumeIndexOfRefraction",ee.Float,!0,be.Fragment),this.registerOutput("refraction",ee.Object,be.Fragment,new ra("refraction",this,1,Kx,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){const i=new nr("Refraction intensity",be.Fragment,ee.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.View&&t(r));i||(i=new nr("view"),i.setAsSystemValue(mr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this._getTexture(),n=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",n,!0),n&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){var l,c;super.bind(e,t,i);const r=this._getTexture();if(!r)return;r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),e.setMatrix(this._refractionMatrixName,r.getRefractionTextureMatrix());let n=1;r.isCube||r.depth&&(n=r.depth);const a=((l=this.volumeIndexOfRefraction.connectInputBlock)==null?void 0:l.value)??((c=this.indexOfRefractionConnectionPoint.connectInputBlock)==null?void 0:c.value)??1.5;e.setFloat4(this._vRefractionInfosName,r.level,1/a,n,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset,1/a);const o=r.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,At.Log2(o)),r.boundingBoxSize){const u=r;e.setVector3("vRefractionPosition",u.boundingBoxPosition),e.setVector3("vRefractionSize",u.boundingBoxSize)}}getCode(e){const t="";return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),this._getTexture()&&(e._samplerDeclaration+=`#ifdef ${this._define3DName} `,e._emitCubeSampler(this._cubeSamplerName,void 0,!0),e._samplerDeclaration+=`#else `,e._emit2DSampler(this._2DSamplerName,void 0,!0),e._samplerDeclaration+=`#endif `),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,ee.Matrix),e.shaderLanguage!==1&&(e._emitFunction("sampleRefraction",` #ifdef ${this._define3DName} #define sampleRefraction(s, c) textureCube(s, c) #else #define sampleRefraction(s, c) texture2D(s, c) #endif `,`//${this.name}`),e._emitFunction("sampleRefractionLod",` #ifdef ${this._define3DName} #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) #else #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) #endif `,`//${this.name}`)),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,ee.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,ee.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,ee.Vector2),e._emitUniformFromString("vRefractionPosition",ee.Vector3),e._emitUniformFromString("vRefractionSize",ee.Vector3),t}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(this.texture.isCube?e=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}"); `:e=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; `,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; `,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; `,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=_a.Parse(e.texture,t,i):this.texture=xe.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}F([Jt("Link refraction to transparency",0,"ADVANCED",{notifiers:{update:!0}})],Kx.prototype,"linkRefractionWithTransparency",void 0);F([Jt("Invert refraction Y",0,"ADVANCED",{notifiers:{update:!0}})],Kx.prototype,"invertRefractionY",void 0);F([Jt("Use thickness as depth",0,"ADVANCED",{notifiers:{update:!0}})],Kx.prototype,"useThicknessAsDepth",void 0);ve("BABYLON.RefractionBlock",Kx);class cw extends qt{constructor(e){super(e,be.Fragment),this._isUnique=!0,this.registerInput("thickness",ee.Float,!1,be.Fragment),this.registerInput("tintColor",ee.Color3,!0,be.Fragment),this.registerInput("translucencyIntensity",ee.Float,!0,be.Fragment),this.registerInput("translucencyDiffusionDist",ee.Color3,!0,be.Fragment),this.registerInput("refraction",ee.Object,!0,be.Fragment,new ra("refraction",this,0,Kx,"RefractionBlock")),this.registerInput("dispersion",ee.Float,!0,be.Fragment),this.registerOutput("subsurface",ee.Object,be.Fragment,new ra("subsurface",this,1,cw,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vTranslucencyColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new nr("SubSurface thickness",be.Fragment,ee.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,r){var g;let n="";const a=t!=null&&t.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",l=t!=null&&t.translucencyIntensity.isConnected?t==null?void 0:t.translucencyIntensity.associatedVariableName:"1.",c=t!=null&&t.translucencyDiffusionDist.isConnected?t==null?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",u=t!=null&&t.refraction.isConnected?(g=t==null?void 0:t.refraction.connectedPoint)==null?void 0:g.ownerBlock:null,h=u!=null&&u.tintAtDistance.isConnected?u.tintAtDistance.associatedVariableName:"1.",d=u!=null&&u.intensity.isConnected?u.intensity.associatedVariableName:"1.",f=u!=null&&u.view.isConnected?u.view.associatedVariableName:"",p=t!=null&&t.dispersion.isConnected?t==null?void 0:t.dispersion.associatedVariableName:"0.0",m=e.shaderLanguage===1;return n+=(u==null?void 0:u.getCode(e))??"",n+=`${m?"var subSurfaceOut: subSurfaceOutParams":"subSurfaceOutParams subSurfaceOut"}; #ifdef SUBSURFACE ${e._declareLocalVar("vThicknessParam",ee.Vector2)} = vec2${e.fSuffix}(0., ${a}); ${e._declareLocalVar("vTintColor",ee.Vector4)} = vec4${e.fSuffix}(${o}, ${h}); ${e._declareLocalVar("vSubSurfaceIntensity",ee.Vector3)} = vec3(${d}, ${l}, 0.); ${e._declareLocalVar("dispersion",ee.Float)} = ${p}; subSurfaceOut = subSurfaceBlock( vSubSurfaceIntensity , vThicknessParam , vTintColor , normalW , specularEnvironmentReflectance #ifdef SS_THICKNESSANDMASK_TEXTURE , vec4${e.fSuffix}(0.) #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY , ${(m?"uniforms.":"")+(i==null?void 0:i._reflectionMatrixName)} #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) , reflectionOut.irradianceVector #endif #if defined(REALTIME_FILTERING) , ${i==null?void 0:i._cubeSamplerName} ${m?`, ${i==null?void 0:i._cubeSamplerName}Sampler`:""} , ${i==null?void 0:i._vReflectionFilteringInfoName} #endif #endif #ifdef USEIRRADIANCEMAP , irradianceSampler ${m?", irradianceSamplerSampler":""} #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) , surfaceAlbedo #endif #ifdef SS_REFRACTION , ${r}.xyz , viewDirectionW , ${f} , ${(m?"uniforms.":"")+(u==null?void 0:u._vRefractionInfosName)} , ${(m?"uniforms.":"")+(u==null?void 0:u._refractionMatrixName)} , ${(m?"uniforms.":"")+(u==null?void 0:u._vRefractionMicrosurfaceInfosName)} , ${m?"uniforms.":""}vLightingIntensity #ifdef SS_LINKREFRACTIONTOTRANSPARENCY , alpha #endif #ifdef ${(u==null?void 0:u._defineLODRefractionAlpha)??"IGNORE"} , NdotVUnclamped #endif #ifdef ${(u==null?void 0:u._defineLinearSpecularRefraction)??"IGNORE"} , roughness #endif , alphaG #ifdef ${(u==null?void 0:u._define3DName)??"IGNORE"} , ${(u==null?void 0:u._cubeSamplerName)??""} ${m?`, ${u==null?void 0:u._cubeSamplerName}Sampler`:""} #else , ${(u==null?void 0:u._2DSamplerName)??""} ${m?`, ${u==null?void 0:u._2DSamplerName}Sampler`:""} #endif #ifndef LODBASEDMICROSFURACE #ifdef ${(u==null?void 0:u._define3DName)??"IGNORE"} , ${(u==null?void 0:u._cubeSamplerName)??""} ${m?`, ${u==null?void 0:u._cubeSamplerName}Sampler`:""} , ${(u==null?void 0:u._cubeSamplerName)??""} ${m?`, ${u==null?void 0:u._cubeSamplerName}Sampler`:""} #else , ${(u==null?void 0:u._2DSamplerName)??""} ${m?`, ${u==null?void 0:u._2DSamplerName}Sampler`:""} , ${(u==null?void 0:u._2DSamplerName)??""} ${m?`, ${u==null?void 0:u._2DSamplerName}Sampler`:""} #endif #endif #ifdef ANISOTROPIC , anisotropicOut #endif #ifdef REALTIME_FILTERING , ${(u==null?void 0:u._vRefractionFilteringInfoName)??""} #endif #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC , vRefractionPosition , vRefractionSize #endif #ifdef SS_DISPERSION , dispersion #endif #endif #ifdef SS_TRANSLUCENCY , ${c} , vTintColor #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE , vec4${e.fSuffix}(0.) #endif #endif ); #ifdef SS_REFRACTION surfaceAlbedo = subSurfaceOut.surfaceAlbedo; #ifdef SS_LINKREFRACTIONTOTRANSPARENCY alpha = subSurfaceOut.alpha; #endif #endif #else subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; #endif `,n}_buildBlock(e){return e.target===be.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}ve("BABYLON.SubSurfaceBlock",cw);const fTt={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class Qo extends qt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,fe.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?be.Fragment:be.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?be.Fragment:be.Vertex}constructor(e){super(e,be.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Re.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",ee.Vector4,!1,be.Vertex),this.registerInput("worldNormal",ee.Vector4,!1,be.Vertex),this.registerInput("view",ee.Matrix,!1),this.registerInput("cameraPosition",ee.Vector3,!1,be.Fragment),this.registerInput("perturbedNormal",ee.Vector4,!0,be.Fragment),this.registerInput("baseColor",ee.Color3,!0,be.Fragment),this.registerInput("metallic",ee.Float,!1,be.Fragment),this.registerInput("roughness",ee.Float,!1,be.Fragment),this.registerInput("ambientOcc",ee.Float,!0,be.Fragment),this.registerInput("opacity",ee.Float,!0,be.Fragment),this.registerInput("indexOfRefraction",ee.Float,!0,be.Fragment),this.registerInput("ambientColor",ee.Color3,!0,be.Fragment),this.registerInput("reflection",ee.Object,!0,be.Fragment,new ra("reflection",this,0,dT,"ReflectionBlock")),this.registerInput("clearcoat",ee.Object,!0,be.Fragment,new ra("clearcoat",this,0,l6,"ClearCoatBlock")),this.registerInput("sheen",ee.Object,!0,be.Fragment,new ra("sheen",this,0,hT,"SheenBlock")),this.registerInput("subsurface",ee.Object,!0,be.Fragment,new ra("subsurface",this,0,cw,"SubSurfaceBlock")),this.registerInput("anisotropy",ee.Object,!0,be.Fragment,new ra("anisotropy",this,0,qz,"AnisotropyBlock")),this.registerInput("iridescence",ee.Object,!0,be.Fragment,new ra("iridescence",this,0,Xk,"IridescenceBlock")),this.registerOutput("ambientClr",ee.Color3,be.Fragment),this.registerOutput("diffuseDir",ee.Color3,be.Fragment),this.registerOutput("specularDir",ee.Color3,be.Fragment),this.registerOutput("clearcoatDir",ee.Color3,be.Fragment),this.registerOutput("sheenDir",ee.Color3,be.Fragment),this.registerOutput("diffuseInd",ee.Color3,be.Fragment),this.registerOutput("specularInd",ee.Color3,be.Fragment),this.registerOutput("clearcoatInd",ee.Color3,be.Fragment),this.registerOutput("sheenInd",ee.Color3,be.Fragment),this.registerOutput("refraction",ee.Color3,be.Fragment),this.registerOutput("lighting",ee.Color3,be.Fragment),this.registerOutput("shadow",ee.Float,be.Fragment),this.registerOutput("alpha",ee.Float,be.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,e===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>UWe),void 0),Ue(()=>Promise.resolve().then(()=>qWe),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>iKe),void 0),Ue(()=>Promise.resolve().then(()=>mKe),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.CameraPosition&&t(r));i||(i=new nr("cameraPosition"),i.setAsSystemValue(mr.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(r=>r.systemValue===mr.View&&t(r));i||(i=new nr("view"),i.setAsSystemValue(mr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Pr.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Pr.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",r.indexOf(".")<0?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const n=e.getScene();if(n.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&Je.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),!!i._areLightsDirty)if(!this.light)du(n,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,qw(n,i);else{const o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};pz(n,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,r){for(let n=0;n=0;gz(n,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+n],r,a)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var h;if(!i)return;const r=i.getScene();this.light?fz(this.light,this._lightId,r,e,!0):hu(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const n=this._scene.ambientColor;n&&e.setColor3("ambientFromScene",n);const a=r.useRightHandedSystem===(r._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,a?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=1,l=((h=this.indexOfRefraction.connectInputBlock)==null?void 0:h.value)??1.5,c=Math.pow((l-o)/(l+o),2);this._metallicReflectanceColor.scaleToRef(c*this._metallicF0Factor,ts.Color3[0]);const u=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,ts.Color3[0],u),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var c;const t=this.worldPosition,i=this.worldNormal,r=`//${this.name}`,n=e.shaderLanguage===1;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const a="v_"+t.associatedVariableName;e._emitVaryingFromString(a,ee.Vector4)&&(e.compilationString+=(n?"vertexOutputs.":"")+`${a} = ${t.associatedVariableName}; `);const o="v_"+i.associatedVariableName;e._emitVaryingFromString(o,ee.Vector4)&&(e.compilationString+=(n?"vertexOutputs.":"")+`${o} = ${i.associatedVariableName}; `);const l=this.reflection.isConnected?(c=this.reflection.connectedPoint)==null?void 0:c.ownerBlock:null;l&&(l.viewConnectionPoint=this.view),e.compilationString+=(l==null?void 0:l.handleVertexSide(e))??"",e._emitVaryingFromString("vClipSpacePosition",ee.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 `,e._injectAtEnd+=(n?"vertexOutputs.":"")+`vClipSpacePosition = ${n?"vertexOutputs.position":"gl_Position"}; `,e._injectAtEnd+=`#endif `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",ee.Vector4)} = ${t.associatedVariableName}; `,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",ee.Matrix)} = ${this.view.associatedVariableName}; `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(e){let i=e.shaderLanguage===1?`var albedoOpacityOut: albedoOpacityOutParams; `:`albedoOpacityOutParams albedoOpacityOut; `;const r=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",n=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return i+=`albedoOpacityOut = albedoOpacityBlock( vec4${e.fSuffix}(${r}, 1.) #ifdef ALBEDO ,vec4${e.fSuffix}(1.) ,vec2${e.fSuffix}(1., 1.) #endif #ifdef OPACITY ,vec4${e.fSuffix}(${n}) ,vec2${e.fSuffix}(1., 1.) #endif ); ${e._declareLocalVar("surfaceAlbedo",ee.Vector3)} = albedoOpacityOut.surfaceAlbedo; ${e._declareLocalVar("alpha",ee.Float)} = albedoOpacityOut.alpha; `,i}_getAmbientOcclusionCode(e){let i=e.shaderLanguage===1?`var aoOut: ambientOcclusionOutParams; `:`ambientOcclusionOutParams aoOut; `;const r=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return i+=`aoOut = ambientOcclusionBlock( #ifdef AMBIENT vec3${e.fSuffix}(${r}), vec4${e.fSuffix}(0., 1.0, 1.0, 0.) #endif ); `,i}_getReflectivityCode(e){const t=e.shaderLanguage===1;let i=t?`var reflectivityOut: reflectivityOutParams; `:`reflectivityOutParams reflectivityOut; `;const r="1.";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,ee.Vector4),i+=`${e._declareLocalVar("baseColor",ee.Vector3)} = surfaceAlbedo; reflectivityOut = reflectivityBlock( vec4${e.fSuffix}(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.) #ifdef METALLICWORKFLOW , surfaceAlbedo , ${(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName} #endif #ifdef REFLECTIVITY , vec3${e.fSuffix}(0., 0., ${r}) , vec4${e.fSuffix}(1.) #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) , aoOut.ambientOcclusionColor #endif #ifdef MICROSURFACEMAP , microSurfaceTexel <== not handled! #endif ); ${e._declareLocalVar("microSurface",ee.Float)} = reflectivityOut.microSurface; ${e._declareLocalVar("roughness",ee.Float)} = reflectivityOut.roughness; #ifdef METALLICWORKFLOW surfaceAlbedo = reflectivityOut.surfaceAlbedo; #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; #endif `,i}_buildBlock(e){var b,C,T,w,P,M,R,I,L,k,V;super._buildBlock(e),this._scene=e.sharedData.scene;const t=e.shaderLanguage===1;this._environmentBRDFTexture||(this._environmentBRDFTexture=Hz(this._scene));const i=this.reflection.isConnected?(b=this.reflection.connectedPoint)==null?void 0:b.ownerBlock:null;if(i&&(i.worldPositionConnectionPoint=this.worldPosition,i.cameraPositionConnectionPoint=this.cameraPosition,i.worldNormalConnectionPoint=this.worldNormal,i.viewConnectionPoint=this.view),e.target!==be.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=`//${this.name}`,n=this.perturbedNormal;let a=this.worldPosition.associatedVariableName,o=this.worldNormal.associatedVariableName;this.generateOnlyFragmentCode?(a=e._getFreeVariableName("globalWorldPos"),e.compilationString+=`${a} = ${this.worldPosition.associatedVariableName}.xyz; `,o=e._getFreeVariableName("globalWorldNormal"),e.compilationString+=`${o} = ${this.worldNormal.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 `,e.compilationString+=`${e._declareLocalVar("vClipSpacePosition",ee.Vector4)} = vec4${e.fSuffix}((vec2${e.fSuffix}(${t?"fragmentInputs.position":"gl_FragCoord.xy"}) / vec2${e.fSuffix}(1.0)) * 2.0 - 1.0, 0.0, 1.0); `,e.compilationString+=`#endif `):(a=(t?"input.":"")+"v_"+a,o=(t?"input.":"")+"v_"+o),this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",ee.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",ee.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",r),e._emitFunctionFromInclude("importanceSampling",r),e._emitFunctionFromInclude("pbrHelperFunctions",r),e._emitFunctionFromInclude("imageProcessingDeclaration",r),e._emitFunctionFromInclude("imageProcessingFunctions",r),e._emitFunctionFromInclude("shadowsFragmentFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",r),e._emitFunctionFromInclude("pbrBRDFFunctions",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingFunctions",r),e._emitFunctionFromInclude("pbrIBLFunctions",r),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",r),e._emitFunctionFromInclude("pbrBlockReflectivity",r),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",r),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",r),e._emitFunctionFromInclude("pbrBlockAnisotropic",r),e._emitUniformFromString("vLightingIntensity",ee.Vector4),i!=null&&i.generateOnlyFragmentCode&&(e.compilationString+=i.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`${e._declareLocalVar(this._vNormalWName,ee.Vector4)} = normalize(${o}); `,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",ee.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${a}.xyz); `),e.compilationString+=`${e._declareLocalVar("geometricNormalW",ee.Vector3)} = ${this._vNormalWName}.xyz; `,e.compilationString+=`${e._declareLocalVar("normalW",ee.Vector3)} = ${n.isConnected?"normalize("+n.associatedVariableName+".xyz)":"geometricNormalW"}; `,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,ee.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",r,{replaceStrings:[{search:/vPositionW/g,replace:a+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(e),e.compilationString+=e._emitCodeFromInclude("depthPrePass",r),e.compilationString+=this._getAmbientOcclusionCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",r),e.compilationString+=`#ifdef UNLIT ${e._declareLocalVar("diffuseBase",ee.Vector3)} = vec3${e.fSuffix}(1., 1., 1.); #else `,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(i==null?void 0:i._define3DName)??"REFLECTIONMAP_3D"}]});const l=this.anisotropy.isConnected?(C=this.anisotropy.connectedPoint)==null?void 0:C.ownerBlock:null;l&&(l.worldPositionConnectionPoint=this.worldPosition,l.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=l.getCode(e,!this.perturbedNormal.isConnected)),i&&i.hasTexture&&(e.compilationString+=i.getCode(e,l?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",r,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(i==null?void 0:i._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(i==null?void 0:i._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(i==null?void 0:i._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(i==null?void 0:i._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(i==null?void 0:i._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(i==null?void 0:i._vReflectionFilteringInfoName)??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",r,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName}]});const c=this.sheen.isConnected?(T=this.sheen.connectedPoint)==null?void 0:T.ownerBlock:null;c&&(e.compilationString+=c.getCode(i,e)),e._emitFunctionFromInclude("pbrBlockSheen",r,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(i==null?void 0:i._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(i==null?void 0:i._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(i==null?void 0:i._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"}]});const u=this.iridescence.isConnected?(w=this.iridescence.connectedPoint)==null?void 0:w.ownerBlock:null;e.compilationString+=Xk.GetCode(u,e),e._emitFunctionFromInclude("pbrBlockIridescence",r,{replaceStrings:[]});const h=this.clearcoat.isConnected?(P=this.clearcoat.connectedPoint)==null?void 0:P.ownerBlock:null,d=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,f=this.perturbedNormal.isConnected&&((R=((M=this.perturbedNormal.connectedPoint)==null?void 0:M.ownerBlock).worldTangent)==null?void 0:R.isConnected),p=this.anisotropy.isConnected&&((I=this.anisotropy.connectedPoint)==null?void 0:I.ownerBlock).worldTangent.isConnected;let m=f||!this.perturbedNormal.isConnected&&p;e.compilationString+=l6.GetCode(e,h,i,a,d,m,o),d&&(m=(h==null?void 0:h.worldTangent.isConnected)??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",r,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(i==null?void 0:i._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(i==null?void 0:i._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(i==null?void 0:i._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(i==null?void 0:i._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(i==null?void 0:i._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:m?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(i==null?void 0:i._define3DName)??"REFLECTIONMAP_3D"}]});const g=this.subsurface.isConnected?(L=this.subsurface.connectedPoint)==null?void 0:L.ownerBlock:null,_=this.subsurface.isConnected?(V=((k=this.subsurface.connectedPoint)==null?void 0:k.ownerBlock).refraction.connectedPoint)==null?void 0:V.ownerBlock:null;_&&(_.viewConnectionPoint=this.view,_.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=cw.GetCode(e,g,i,a),e._emitFunctionFromInclude("pbrBlockSubSurface",r,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(i==null?void 0:i._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(i==null?void 0:i._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(i==null?void 0:i._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(_==null?void 0:_._define3DName)??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(_==null?void 0:_._defineLODRefractionAlpha)??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(_==null?void 0:_._defineLinearSpecularRefraction)??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(_==null?void 0:_._defineOppositeZ)??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",r),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:new RegExp(`${t?"input.":""}vPositionW`,"g"),replace:a+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{repeatKey:"maxSimultaneousLights",substitutionVars:`${t?"input.":""}vPositionW,${a}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",r),e.compilationString+=`#endif `;const y=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:`vec3${e.fSuffix}(0., 0., 0.)`;let v=Pr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();v.indexOf(".")===-1&&(v+=".");let x=[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:new RegExp(`${t?"uniforms.":""}vAmbientColor`,"g"),replace:y+` * ${t?"uniforms.":""}ambientFromScene`},{search:new RegExp(`${t?"uniforms.":""}vAmbientInfos.w`,"g"),replace:v}];t&&(x[0]={search:/var finalEmissive[\s\S]*?finalEmissive\*=uniforms.vLightingIntensity\.y;/g,replace:""}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",r,{replaceStrings:x}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",r,{replaceStrings:[{search:/finalEmissive/g,replace:`vec3${e.fSuffix}(0.)`}]}),t?x=[{search:/mesh.visibility/g,replace:"1."}]:x=[{search:/visibility/g,replace:"1."}],e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",r,{replaceStrings:x});const A=t?"fragmentOutputs.color":"gl_FragColor";x=[{search:new RegExp(`${t?"fragmentInputs.":""}vNormalW`,"g"),replace:this._vNormalWName},{search:new RegExp(`${t?"fragmentInputs.":""}vPositionW`,"g"),replace:a},{search:/albedoTexture\.rgb;/g,replace:`vec3${e.fSuffix}(1.); ${A}.rgb = toGammaSpace(${A}.rgb); `}],e.compilationString+=e._emitCodeFromInclude("pbrDebug",r,{replaceStrings:x});for(const H of this._outputs)if(H.hasEndpoints){const j=fTt[H.name];if(j){const[z,K]=j;K&&(e.compilationString+=`#if ${K} `),e.compilationString+=`${e._declareOutput(H)} = ${z}; `,K&&(e.compilationString+=`#else `,e.compilationString+=`${e._declareOutput(H)} = vec3${e.fSuffix}(0.); `,e.compilationString+=`#endif `)}else fe.Error(`There's no remapping for the ${H.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; `,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; `,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; `,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; `,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; `,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; `,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; `,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; `,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; `,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; `,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; `,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; `,e+=`${this._codeVariableName}.unlit = ${this.unlit}; `,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; `,e+=`${this._codeVariableName}.debugMode = ${this.debugMode}; `,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit}; `,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor}; `,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}F([Jt("Direct lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Qo.prototype,"directIntensity",void 0);F([Jt("Environment lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Qo.prototype,"environmentIntensity",void 0);F([Jt("Specular highlights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Qo.prototype,"specularIntensity",void 0);F([Jt("Light falloff",4,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Pr.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Pr.LIGHTFALLOFF_GLTF},{label:"Standard",value:Pr.LIGHTFALLOFF_STANDARD}]})],Qo.prototype,"lightFalloff",void 0);F([Jt("Alpha Testing",0,"OPACITY")],Qo.prototype,"useAlphaTest",void 0);F([Jt("Alpha CutOff",1,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],Qo.prototype,"alphaTestCutoff",void 0);F([Jt("Alpha blending",0,"OPACITY")],Qo.prototype,"useAlphaBlending",void 0);F([Jt("Radiance over alpha",0,"RENDERING",{notifiers:{update:!0}})],Qo.prototype,"useRadianceOverAlpha",void 0);F([Jt("Specular over alpha",0,"RENDERING",{notifiers:{update:!0}})],Qo.prototype,"useSpecularOverAlpha",void 0);F([Jt("Specular anti-aliasing",0,"RENDERING",{notifiers:{update:!0}})],Qo.prototype,"enableSpecularAntiAliasing",void 0);F([Jt("Realtime filtering",0,"RENDERING",{notifiers:{update:!0}})],Qo.prototype,"realTimeFiltering",void 0);F([Jt("Realtime filtering quality",4,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],Qo.prototype,"realTimeFilteringQuality",void 0);F([Jt("Energy Conservation",0,"ADVANCED",{notifiers:{update:!0}})],Qo.prototype,"useEnergyConservation",void 0);F([Jt("Radiance occlusion",0,"ADVANCED",{notifiers:{update:!0}})],Qo.prototype,"useRadianceOcclusion",void 0);F([Jt("Horizon occlusion",0,"ADVANCED",{notifiers:{update:!0}})],Qo.prototype,"useHorizonOcclusion",void 0);F([Jt("Unlit",0,"ADVANCED",{notifiers:{update:!0}})],Qo.prototype,"unlit",void 0);F([Jt("Force normal forward",0,"ADVANCED",{notifiers:{update:!0}})],Qo.prototype,"forceNormalForward",void 0);F([Jt("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Qo._OnGenerateOnlyFragmentCodeChanged}})],Qo.prototype,"generateOnlyFragmentCode",void 0);F([Jt("Debug mode",4,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],Qo.prototype,"debugMode",void 0);F([Jt("Split position",1,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],Qo.prototype,"debugLimit",void 0);F([Jt("Output factor",1,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],Qo.prototype,"debugFactor",void 0);ve("BABYLON.PBRMetallicRoughnessBlock",Qo);class WHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("left",ee.AutoDetect),this.registerInput("right",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(ee.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.shaderLanguage===0?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); `:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName}); `,this}}ve("BABYLON.ModBlock",WHe);class KHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("row0",ee.Vector4),this.registerInput("row1",ee.Vector4),this.registerInput("row2",ee.Vector4),this.registerInput("row3",ee.Vector4),this.registerOutput("output",ee.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new nr("row0");e.value=new mt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new nr("row1");e.value=new mt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new nr("row2");e.value=new mt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new nr("row3");e.value=new mt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,r=this.row1,n=this.row2,a=this.row3,o=e.shaderLanguage===1?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}); `,this}}ve("BABYLON.MatrixBuilder",KHe);var Pd;(function(s){s[s.Equal=0]="Equal",s[s.NotEqual=1]="NotEqual",s[s.LessThan=2]="LessThan",s[s.GreaterThan=3]="GreaterThan",s[s.LessOrEqual=4]="LessOrEqual",s[s.GreaterOrEqual=5]="GreaterOrEqual",s[s.Xor=6]="Xor",s[s.Or=7]="Or",s[s.And=8]="And"})(Pd||(Pd={}));class HHe extends qt{constructor(e){super(e,be.Neutral),this.condition=Pd.LessThan,this.registerInput("a",ee.Float),this.registerInput("b",ee.Float),this.registerInput("true",ee.AutoDetect,!0),this.registerInput("false",ee.AutoDetect,!0),this.registerOutput("output",ee.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=ee.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case Pd.Equal:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)}; `;break}case Pd.NotEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)}; `;break}case Pd.LessThan:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)}; `;break}case Pd.LessOrEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)}; `;break}case Pd.GreaterThan:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)}; `;break}case Pd.GreaterOrEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)}; `;break}case Pd.Xor:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)}; `;break}case Pd.Or:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)}; `;break}case Pd.And:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)}; `;break}}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${Pd[this.condition]}; `}}ve("BABYLON.ConditionalBlock",HHe);class n_e extends qt{constructor(e){super(e,be.Neutral),this.octaves=6,this.registerInput("seed",ee.AutoDetect),this.registerInput("chaos",ee.AutoDetect,!0),this.registerInput("offsetX",ee.Float,!0),this.registerInput("offsetY",ee.Float,!0),this.registerInput("offsetZ",ee.Float,!0),this.registerOutput("output",ee.Float),this._inputs[0].acceptedConnectionPointTypes.push(ee.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(ee.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var l,c,u;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let t=` float cloudRandom(float p) { float temp = fract(p * 0.011); temp *= temp + 7.5; temp *= temp + temp; return fract(temp); } // Based on Morgan McGuire @morgan3d // https://www.shadertoy.com/view/4dS3Wd float cloudNoise2(vec2 x, vec2 chaos) { vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); vec2 i = floor(x); vec2 f = fract(x); float n = dot(i, step); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), u.y ); } float cloudNoise3(vec3 x, vec3 chaos) { vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); vec3 i = floor(x); vec3 f = fract(x); float n = dot(i, step); vec3 u = f * f * (3.0 - 2.0 * f); return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); }`,i=` float fbm2(vec2 st, vec2 chaos) { // Initial values float value = 0.0; float amplitude = .5; float frequency = 0.; // Loop of octaves vec2 tempST = st; for (int i = 0; i < OCTAVES; i++) { value += amplitude * cloudNoise2(tempST, chaos); tempST *= 2.0; amplitude *= 0.5; } return value; } float fbm3(vec3 x, vec3 chaos) { // Initial values float value = 0.0; float amplitude = 0.5; vec3 tempX = x; for (int i = 0; i < OCTAVES; i++) { value += amplitude * cloudNoise3(tempX, chaos); tempX = tempX * 2.0; amplitude *= 0.5; } return value; }`;e.shaderLanguage===1&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const r=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,r).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");const n=e._getFreeVariableName("st"),a=((l=this.seed.connectedPoint)==null?void 0:l.type)||ee.Vector3;e.compilationString+=`${e._declareLocalVar(n,a)} = ${this.seed.associatedVariableName}; `,this.offsetX.isConnected&&(e.compilationString+=`${n}.x += 0.1 * ${this.offsetX.associatedVariableName}; `),this.offsetY.isConnected&&(e.compilationString+=`${n}.y += 0.1 * ${this.offsetY.associatedVariableName}; `),this.offsetZ.isConnected&&a===ee.Vector3&&(e.compilationString+=`${n}.z += 0.1 * ${this.offsetZ.associatedVariableName}; `);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const h=e.fSuffix;o=((c=this.seed.connectedPoint)==null?void 0:c.type)===ee.Vector2?`vec2${h}(0., 0.)`:`vec3${h}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${r}${((u=this.seed.connectedPoint)==null?void 0:u.type)===ee.Vector2?"2":"3"}(${n}, ${o}); `,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; `}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}F([Jt("Octaves",2)],n_e.prototype,"octaves",void 0);ve("BABYLON.CloudBlock",n_e);class jHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("seed",ee.Vector2),this.registerInput("offset",ee.Float),this.registerInput("density",ee.Float),this.registerOutput("output",ee.Float),this.registerOutput("cells",ee.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 p){ p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))); return fract(sin(p)*18.5453); } `;e.shaderLanguage===1&&(t=e._babylonSLtoWGSL(t)),e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ vec2 n = floor(seed * density); vec2 f = fract(seed * density); vec3 m = vec3( 8.0 ); for( int j=-1; j<=1; j++ ){ for( int i=-1; i<=1; i++ ){ vec2 g = vec2( float(i), float(j) ); vec2 o = voronoiRandom( n + g); vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o)); float d = dot( r, r ); if( di.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?((e=this.sourceY.connectedPoint)==null?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(e=this.sourceZ)!=null&&e.isConnected?((t=this.sourceY.connectedPoint)==null?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return e!=null&&e.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e;return((e=this._getImageSourceBlock(this.sourceY))==null?void 0:e.samplerName)??null}get samplerZName(){var e;return((e=this._getImageSourceBlock(this.sourceZ))==null?void 0:e.samplerName)??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const t=this.texture.getScene()??Rt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const t=this.texture.getScene()??Rt.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,be.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",ee.AutoDetect,!1),this.registerInput("normal",ee.AutoDetect,!1),this.registerInput("sharpness",ee.Float,!0),this.registerInput("source",ee.Object,!0,be.VertexAndFragment,new ra("source",this,0,y0,"ImageSourceBlock")),this.registerInput("sourceY",ee.Object,!0,be.VertexAndFragment,new ra("sourceY",this,0,y0,"ImageSourceBlock")),t||this.registerInput("sourceZ",ee.Object,!0,be.VertexAndFragment,new ra("sourceZ",this,0,y0,"ImageSourceBlock")),this.registerOutput("rgba",ee.Color4,be.Neutral),this.registerOutput("rgb",ee.Color3,be.Neutral),this.registerOutput("r",ee.Float,be.Neutral),this.registerOutput("g",ee.Float,be.Neutral),this.registerOutput("b",ee.Float,be.Neutral),this.registerOutput("a",ee.Float,be.Neutral),this.registerOutput("level",ee.Float,be.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ee.Color3|ee.Vector3|ee.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,n=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,n,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return e.shaderLanguage===1?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return i.shaderLanguage===1?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,r=this.samplerZName??t,n=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),l=e._getFreeVariableName("z"),c=e._getFreeVariableName("w"),u=e._getFreeVariableName("n"),h=e._getFreeVariableName("uvx"),d=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=` ${e._declareLocalVar(u,ee.Vector3)} = ${this.normal.associatedVariableName}.xyz; ${e._declareLocalVar(h,ee.Vector2)} = ${this.position.associatedVariableName}.yz; ${e._declareLocalVar(d,ee.Vector2)} = ${this.position.associatedVariableName}.zx; ${e._declareLocalVar(f,ee.Vector2)} = ${this.position.associatedVariableName}.xy; `,this.projectAsCube&&(e.compilationString+=` ${h}.xy = ${h}.yx; if (${u}.x >= 0.0) { ${h}.x = -${h}.x; } if (${u}.y < 0.0) { ${d}.y = -${d}.y; } if (${u}.z < 0.0) { ${f}.x = -${f}.x; } `);const p=e.fSuffix;e.compilationString+=` ${e._declareLocalVar(a,ee.Vector4)} = ${this._generateTextureSample(t,h,e)}; ${e._declareLocalVar(o,ee.Vector4)} = ${this._generateTextureSample(i,d,e)}; ${e._declareLocalVar(l,ee.Vector4)} = ${this._generateTextureSample(r,f,e)}; // blend weights ${e._declareLocalVar(c,ee.Vector3)} = pow(abs(${u}), vec3${p}(${n})); // blend and return ${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = (${a}*${c}.x + ${o}*${c}.y + ${l}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); `}_generateConversionCode(e,t,i){let r="";e.shaderLanguage===1&&(t.type===ee.Vector3||t.type===ee.Color3)&&(r="Vec3"),i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName} ${t.associatedVariableName} = toGammaSpace${r}(${t.associatedVariableName}); #endif `),e.compilationString+=`#ifdef ${this._gammaDefineName} ${t.associatedVariableName} = toLinearSpace${r}(${t.associatedVariableName}); #endif `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${e.shaderLanguage===1?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r}; `,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(e.shaderLanguage===1?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,ee.Float),this._generateTextureLookup(e);for(const i of this._outputs)i.hasEndpoints&&i.name!=="level"&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; `,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; `,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; `,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; `,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); `,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; `,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; `,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; `,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; `,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; `,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; `,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; `,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; `,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; `,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; `),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=xe.Parse(e.texture,t,i))}}F([Jt("Project as cube",0,"ADVANCED",{notifiers:{update:!0}})],Ree.prototype,"projectAsCube",void 0);ve("BABYLON.TriPlanarBlock",Ree);class YHe extends Ree{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return t.shaderLanguage===1?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return e.shaderLanguage===1?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dxValue"),a=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),c=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),h=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),f=e._getFreeVariableName("w");let p="ivec3",m="dFdx",g="dFdy";const _=e.fSuffix;e.shaderLanguage===1&&(p="vec3",m="dpdx",g="dpdy"),e.compilationString+=` // grab coord derivatives for texturing ${e._declareLocalVar(n,ee.Vector3)} = ${m}(${this.position.associatedVariableName}.xyz); ${e._declareLocalVar(a,ee.Vector3)} = ${g}(${this.position.associatedVariableName}.xyz); ${e._declareLocalVar(o,ee.Vector3)} = abs(${this.normal.associatedVariableName}.xyz); // determine major axis (in x; yz are following axis) ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${p}(0,1,2)`,`${e._generateTernary(`${p}(1,2,0)`,`${p}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; // determine minor axis (in x; yz are following axis) ${this._declareLocalVarAsVec3I(c,e)} = ${e._generateTernary(`${p}(0,1,2)`,`${e._generateTernary(`${p}(1,2,0)`,`${p}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; // determine median axis (in x; yz are following axis) ${this._declareLocalVarAsVec3I(u,e)} = ${p}(3) - ${c} - ${l}; // project+fetch ${e._declareLocalVar(h,ee.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${_}(${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), vec2${_}(${n}[${l}.y],${n}[${l}.z]), vec2${_}(${a}[${l}.y],${a}[${l}.z])); ${e._declareLocalVar(d,ee.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${_}(${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), vec2${_}(${n}[${u}.y],${n}[${u}.z]), vec2${_}(${a}[${u}.y],${a}[${u}.z])); // blend factors ${e._declareLocalVar(f,ee.Vector2)} = vec2${_}(${o}[${l}.x],${o}[${u}.x]); // make local support ${f} = clamp( (${f}-0.5773)/(1.0-0.5773), vec2${_}(0.0), vec2${_}(1.0) ); // shape transition ${f} = pow( ${f}, vec2${_}(${r}/8.0) ); // blend and return ${e._declareLocalVar(this._tempTextureRead,ee.Vector4)} = (${h}*${f}.x + ${d}*${f}.y) / (${f}.x + ${f}.y); `}}ve("BABYLON.BiPlanarBlock",YHe);class QHe extends qt{constructor(e){super(e,be.Neutral),this.registerInput("input",ee.Matrix),this.registerOutput("output",ee.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = determinant(${i.associatedVariableName}); `,this}}ve("BABYLON.MatrixDeterminantBlock",QHe);class $He extends qt{constructor(e){super(e,be.Neutral),this.registerInput("input",ee.Matrix),this.registerOutput("output",ee.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName}); `,this}}ve("BABYLON.MatrixTransposeBlock",$He);var nde;(function(s){s[s.None=0]="None",s[s.Normal=1]="Normal",s[s.Tangent=2]="Tangent",s[s.VertexColor=3]="VertexColor",s[s.UV1=4]="UV1",s[s.UV2=5]="UV2",s[s.UV3=6]="UV3",s[s.UV4=7]="UV4",s[s.UV5=8]="UV5",s[s.UV6=9]="UV6"})(nde||(nde={}));class a_e extends qt{constructor(e){super(e,be.Neutral),this.attributeType=0,this.registerInput("input",ee.AutoDetect),this.registerInput("fallback",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var r;if(this.attributeType)return;const i=t.ownerBlock;if(i instanceof nr&&i.isAttribute)switch(i.name){case"color":this.attributeType=3;break;case"normal":this.attributeType=1;break;case"tangent":this.attributeType=2;break;case"uv":this.attributeType=4;break;case"uv2":this.attributeType=5;break;case"uv3":this.attributeType=6;break;case"uv4":this.attributeType=7;break;case"uv5":this.attributeType=8;break;case"uv6":this.attributeType=9;break}else if(i instanceof e_e)switch((r=this.input.connectedPoint)==null?void 0:r.name){case"normalOutput":this.attributeType=1;break;case"tangentOutput":this.attributeType=2;break;case"uvOutput":this.attributeType=4;break}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case 3:t="VERTEXCOLOR_NME";break;case 1:t="NORMAL";break;case 2:t="TANGENT";break;case 4:t="UV1";break;case 5:t="UV2";break;case 6:t="UV3";break;case 7:t="UV4";break;case 8:t="UV5";break;case 9:t="UV6";break}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t} `),e.compilationString+=`${i} = ${this.input.associatedVariableName}; `,t&&(e.compilationString+=`#else `,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; `,e.compilationString+=`#endif `),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??0}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType}; `,e}}F([Jt("Attribute lookup",4,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:0},{label:"Normal",value:1},{label:"Tangent",value:2},{label:"Vertex Color",value:3},{label:"UV1",value:4},{label:"UV2",value:5},{label:"UV3",value:6},{label:"UV4",value:7},{label:"UV5",value:8},{label:"UV6",value:9}]})],a_e.prototype,"attributeType",void 0);ve("BABYLON.MeshAttributeExistsBlock",a_e);var Tn;(function(s){s[s.EaseInSine=0]="EaseInSine",s[s.EaseOutSine=1]="EaseOutSine",s[s.EaseInOutSine=2]="EaseInOutSine",s[s.EaseInQuad=3]="EaseInQuad",s[s.EaseOutQuad=4]="EaseOutQuad",s[s.EaseInOutQuad=5]="EaseInOutQuad",s[s.EaseInCubic=6]="EaseInCubic",s[s.EaseOutCubic=7]="EaseOutCubic",s[s.EaseInOutCubic=8]="EaseInOutCubic",s[s.EaseInQuart=9]="EaseInQuart",s[s.EaseOutQuart=10]="EaseOutQuart",s[s.EaseInOutQuart=11]="EaseInOutQuart",s[s.EaseInQuint=12]="EaseInQuint",s[s.EaseOutQuint=13]="EaseOutQuint",s[s.EaseInOutQuint=14]="EaseInOutQuint",s[s.EaseInExpo=15]="EaseInExpo",s[s.EaseOutExpo=16]="EaseOutExpo",s[s.EaseInOutExpo=17]="EaseInOutExpo",s[s.EaseInCirc=18]="EaseInCirc",s[s.EaseOutCirc=19]="EaseOutCirc",s[s.EaseInOutCirc=20]="EaseInOutCirc",s[s.EaseInBack=21]="EaseInBack",s[s.EaseOutBack=22]="EaseOutBack",s[s.EaseInOutBack=23]="EaseInOutBack",s[s.EaseInElastic=24]="EaseInElastic",s[s.EaseOutElastic=25]="EaseOutElastic",s[s.EaseInOutElastic=26]="EaseInOutElastic"})(Tn||(Tn={}));class ZHe extends qt{constructor(e){super(e,be.Neutral),this.type=Tn.EaseInOutSine,this.registerInput("input",ee.AutoDetect),this.registerOutput("output",ee.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ee.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ee.Object),this._inputs[0].excludedConnectionPointTypes.push(ee.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t,i){if(t==="float"||t==="f32")return this._duplicateEntryDirect(e);const r=parseInt(t.replace("vec",""));let n=i?` var ret: vec${r}f = vec${r}f(0.0); `:` vec${r} ret = vec${r}(0.0); `;for(let a=1;a<=r;a++)n+=this._duplicateEntry(e,a===1?"x":a===2?"y":a===3?"z":"w")+`; `;return n+=`return ret; `,n}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",r="";const n=e._getShaderType(this.input.type),a=e.shaderLanguage===1;switch(r=Tn[this.type]+"_"+n.replace("<","").replace(">",""),this.type){case Tn.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case Tn.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case Tn.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case Tn.EaseInQuad:i="return v * v";break;case Tn.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case Tn.EaseInOutQuad:{const o=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,n,a);break}case Tn.EaseInCubic:i="return v * v * v";break;case Tn.EaseOutCubic:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",n,a);break}case Tn.EaseInOutCubic:{const o=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,n,a);break}case Tn.EaseInQuart:i="return v * v * v * v";break;case Tn.EaseOutQuart:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",n,a);break}case Tn.EaseInOutQuart:{const o=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,n,a);break}case Tn.EaseInQuint:i="return v * v * v * v * v";break;case Tn.EaseOutQuint:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",n,a);break}case Tn.EaseInOutQuint:{const o=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,n,a);break}case Tn.EaseInExpo:{const o=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(o,n,a);break}case Tn.EaseOutExpo:{const o=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(o,n,a);break}case Tn.EaseInOutExpo:{const o=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(o,n,a);break}case Tn.EaseInCirc:{i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",n,a);break}case Tn.EaseOutCirc:{i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",n,a);break}case Tn.EaseInOutCirc:{const o=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,n,a);break}case Tn.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case Tn.EaseOutBack:{i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",n,a);break}case Tn.EaseInOutBack:{const o=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,n,a);break}case Tn.EaseInElastic:{const o=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(o,n,a);break}case Tn.EaseOutElastic:{const o=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(o,n,a);break}case Tn.EaseInOutElastic:{const o=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(o,n,a);break}}return a?e._emitFunction(r,`fn ${r}(v: ${n}) -> ${n} {${i};} `,""):e._emitFunction(r,`${n} ${r}(${n} v) {${i};} `,""),e.compilationString+=e._declareOutput(t)+` = ${r}(${this.input.associatedVariableName}); `,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${Tn[this.type]}; `}}ve("BABYLON.CurveBlock",ZHe);class pTt{optimize(e,t){}}class mTt{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(i!==void 0)return i.get(t)}set(e,t,i){let r=this.mm.get(e);r===void 0&&this.mm.set(e,r=new Map),r.set(t,i)}}class gTt{get standalone(){var e;return((e=this._options)==null?void 0:e.standalone)??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){var e;return((e=this._options)==null?void 0:e.doNotInjectCode)??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??Rt.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new mTt,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add(r=>{var a,o;const n=(a=r.subMesh)==null?void 0:a.getMesh();n&&!this._meshes.has(n)&&this._meshes.set(n,n.onDisposeObservable.add(l=>{const c=this._subMeshToEffect.keys();for(let u=c.next();u.done!==!0;u=c.next()){const h=u.value;(h==null?void 0:h.getMesh())===l&&(this._subMeshToEffect.delete(h),this._deleteDepthWrapperEffect(h))}})),((o=this._subMeshToEffect.get(r.subMesh))==null?void 0:o[0])!==r.effect&&(this._subMeshToEffect.set(r.subMesh,[r.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(r.subMesh))})}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach(i=>{var r;(r=i.mainDrawWrapper.effect)==null||r.dispose()}),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){var a;const r=(a=this._subMeshToDepthWrapper.mm.get(e))==null?void 0:a.get(t);if(!r)return null;let n=r.drawWrapper[i];return n||(n=r.drawWrapper[i]=new Ro(this._scene.getEngine()),n.setEffect(r.mainDrawWrapper.effect,r.mainDrawWrapper.defines)),n}isReadyForSubMesh(e,t,i,r,n){var a;return this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,r)?!1:((a=this._makeEffect(e,t,i,n))==null?void 0:a.isReady())??!1}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();t.done!==!0;t=e.next()){const[i,r]=t.value;i.onDisposeObservable.remove(r)}}_makeEffect(e,t,i,r){var p,m;const n=this._scene.getEngine(),a=this._subMeshToEffect.get(e);if(!a)return null;const[o,l]=a;let c=this._subMeshToDepthWrapper.get(e,i);if(!c){const g=new Ro(n);g.defines=((p=e._getDrawWrapper(l))==null?void 0:p.defines)??null,c={drawWrapper:[],mainDrawWrapper:g,depthDefines:"",token:gh()},c.drawWrapper[r]=g,this._subMeshToDepthWrapper.set(e,i,c)}const u=t.join(` `);if(c.mainDrawWrapper.effect&&u===c.depthDefines)return c.mainDrawWrapper.effect;c.depthDefines=u;const h=o.getUniformNames().slice();let d=o.vertexSourceCodeBeforeMigration,f=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const g=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",_=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",y=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",v="#include",x="#include";o.shaderLanguage===0?d=d.replace(/void\s+?main/g,` ${x} void main`):d=d.replace(/@vertex/g,` ${x} @vertex`),d=d.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,g),d.indexOf("#define SHADOWDEPTH_METRIC")!==-1?d=d.replace(/#define SHADOWDEPTH_METRIC/g,_):d=d.replace(/}\s*$/g,_+` }`),d=d.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const A=f.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||f.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,b=f.indexOf("#define SHADOWDEPTH_FRAGMENT")!==-1;let C="";A?f=f.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,y):C=y+` `,f=f.replace(/void\s+?main/g,zi.IncludesShadersStore.shadowMapFragmentExtraDeclaration+` void main`),b?f=f.replace(/#define SHADOWDEPTH_FRAGMENT/g,v):C+=v+` `,C&&(f=f.replace(/}\s*$/g,C+"}")),h.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}c.mainDrawWrapper.effect=n.createEffect({vertexSource:d,fragmentSource:f,vertexToken:c.token,fragmentToken:c.token},{attributes:o.getAttributesNames(),uniformsNames:h,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:u+` `+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},n);for(let g=0;g0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof D){const t=[];return e.forEach(r=>{t.push(r.flatMap(n=>[n.x,n.y,n.z]))}),t}else{if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach(i=>{t.push(Array.from(i))}),t}}return[]}static OmitZeroLengthPredicate(e,t,i){const r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),r.length===0?null:r}static OmitDuplicatesPredicate(e,t,i,r){const n=[];return Cs._SearchInPoints(e,t,r)||n.push([e,t]),Cs._SearchInPoints(t,i,r)||n.push([t,i]),Cs._SearchInPoints(i,e,r)||n.push([i,e]),n.length===0?null:n}static _SearchInPoints(e,t,i){var r,n,a;for(const o of i)for(let l=0;l{const a=r.getVerticesData($.PositionKind),o=r.getIndices();if(a&&o)for(let l=0,c=0;l[t.x,t.y,t.z])}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){if(e.length===0)return 0;let t;typeof e[0]=="number"?t=Cs.ToVector3Array(e):t=e;const i=se.Vector3[0];let r=0;for(let n=0;n{n.length>t?Cs.SegmentizeSegmentByCount(n.point1,n.point2,Math.ceil(n.length/t)).forEach(o=>{r.push(o)}):(r.push(n.point1),r.push(n.point2))}),r}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?Cs.ToVector3Array(e):e,r=Cs.GetLineLength(i)/t;return Cs.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){const t=[];for(let i=0;ir.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){const n=t*i;let a=0,o=0;const l=e.length;for(let u=0;u[n.x,n.y,n.z])}static GetArrowCap(e,t,i,r,n,a=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,n,a,o]}}static GetPointsFromText(e,t,i,r,n=0,a=!0){const o=[],l=u1e(e,t,i,r);for(const c of l){for(const u of c.paths){const h=[],d=u.getPoints();for(const f of d)h.push(f.x,f.y,n);o.push(h)}if(a)for(const u of c.holes){const h=[],d=u.getPoints();for(const f of d)h.push(f.x,f.y,n);o.push(h)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,r=0;in?n:t.length,o=Math.ceil(t.length/n);o>1&&(t=[...t,...Array(a*o-t.length).fill(t[0])]);const l=Cs.Color3toRGBAUint8(t),c=new yn(l,a,o,vt.TEXTUREFORMAT_RGBA,r,!1,!0,i);return c.name=e,c}static PrepareEmptyColorsTexture(e){if(!Rl.EmptyColorsTexture){const t=new Uint8Array(4);Rl.EmptyColorsTexture=new yn(t,1,1,vt.TEXTUREFORMAT_RGBA,e,!1,!1,yn.NEAREST_NEAREST),Rl.EmptyColorsTexture.name="grlEmptyColorsTexture"}return Rl.EmptyColorsTexture}static DisposeEmptyColorsTexture(){var e;(e=Rl.EmptyColorsTexture)==null||e.dispose(),Rl.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class JHe extends _s{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}}class f_ extends fu{constructor(e,t,i){i=i||{color:Rl.DEFAULT_COLOR};const r=new JHe;r.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,r.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,r.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===1,r.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,r.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,f_.GREASED_LINE_MATERIAL_NAME,200,r),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?Rl.DEFAULT_WIDTH_ATTENUATED:Rl.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??0,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??yn.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new we(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=Cs.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??Rl.DEFAULT_COLOR,Cs.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{Cs.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_textureSize",size:2,type:"vec2"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` uniform vec4 grl_aspect_resolution_lineWidth; uniform mat4 grl_projection; `:"",fragment:` uniform vec4 grl_dashOptions; uniform vec2 grl_textureSize; uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; uniform vec3 grl_singleColor; `}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const n=this._scene.activeCamera;if(n){const o=n.getProjectionMatrix();e.updateMatrix("grl_projection",o)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const a=se.Vector4[0];a.x=this._aspect,a.y=this._resolution.x,a.z=this._resolution.y,a.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",a)}const t=se.Vector4[0];t.x=Cs.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=se.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=Cs.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const r=this.colorsTexture??Rl.EmptyColorsTexture;e.setTexture("grl_colors",r),e.updateFloat2("grl_textureSize",(r==null?void 0:r.getSize().width)??1,(r==null?void 0:r.getSize().height)??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===1,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return f_.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if(e==="vertex"){const t={CUSTOM_VERTEX_DEFINITIONS:` attribute float grl_widths; attribute vec3 grl_offsets; attribute float grl_colorPointers; varying float grlCounters; varying float grlColorPointer; #ifdef GREASED_LINE_CAMERA_FACING attribute vec4 grl_previousAndSide; attribute vec4 grl_nextAndCounters; vec2 grlFix( vec4 i, float aspect ) { vec2 res = i.xy / i.w; res.x *= aspect; return res; } #else attribute vec3 grl_slopes; attribute float grl_counters; #endif `,CUSTOM_VERTEX_UPDATE_POSITION:` #ifdef GREASED_LINE_CAMERA_FACING vec3 grlPositionOffset = grl_offsets; positionUpdated += grlPositionOffset; #else positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); #endif `,CUSTOM_VERTEX_MAIN_END:` grlColorPointer = grl_colorPointers; #ifdef GREASED_LINE_CAMERA_FACING float grlAspect = grl_aspect_resolution_lineWidth.x; float grlBaseWidth = grl_aspect_resolution_lineWidth.w; vec3 grlPrevious = grl_previousAndSide.xyz; float grlSide = grl_previousAndSide.w; vec3 grlNext = grl_nextAndCounters.xyz; grlCounters = grl_nextAndCounters.w; mat4 grlMatrix = viewProjection * finalWorld; vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); vec2 grlNextP = grlFix( grlNextPos, grlAspect ); float grlWidth = grlBaseWidth * grl_widths; vec2 grlDir; if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); else { vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); grlDir = normalize( grlDir1 + grlDir2 ); } vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM grlNormal.xy *= -.5 * grlWidth; #else grlNormal.xy *= .5 * grlWidth; #endif grlNormal *= grl_projection; #ifdef GREASED_LINE_SIZE_ATTENUATION grlNormal.xy *= grlFinalPosition.w; grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; #endif grlFinalPosition.xy += grlNormal.xy * grlSide; gl_Position = grlFinalPosition; vPositionW = vec3(grlFinalPosition); #else grlCounters = grl_counters; #endif `};return this._cameraFacing&&(t["!gl_Position\\=viewProjection\\*worldPos;"]="//"),t}return e==="fragment"?{CUSTOM_FRAGMENT_DEFINITIONS:` varying float grlCounters; varying float grlColorPointer; uniform sampler2D grl_colors; `,CUSTOM_FRAGMENT_MAIN_END:` float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; float grlUseDash = grl_dashOptions.x; float grlDashArray = grl_dashOptions.y; float grlDashOffset = grl_dashOptions.z; float grlDashRatio = grl_dashOptions.w; gl_FragColor.a *= step(grlCounters, grlVisibility); if( gl_FragColor.a == 0. ) discard; if(grlUseDash == 1.){ gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); if (gl_FragColor.a == 0.) discard; } #ifdef GREASED_LINE_HAS_COLOR if (grlColorMode == 0.) { gl_FragColor.rgb = grl_singleColor; } else if (grlColorMode == 1.) { gl_FragColor.rgb += grl_singleColor; } else if (grlColorMode == 2.) { gl_FragColor.rgb *= grl_singleColor; } #else if (grlUseColors == 1.) { #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); #else vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0)); vec4 grlColor = texture2D(grl_colors, lookup, 0.0); #endif if (grlColorMode == 0.) { gl_FragColor = grlColor; } else if (grlColorMode == 1.) { gl_FragColor += grlColor; } else if (grlColorMode == 2.) { gl_FragColor *= grlColor; } } #endif `}:null}dispose(){var e;(e=this.colorsTexture)==null||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var n,a,o;const r=((n=this._colors)==null?void 0:n.length)??0;if(this._colors=e,e===null||e.length===0){(a=this.colorsTexture)==null||a.dispose();return}if(!(t&&!i))if(this.colorsTexture&&r===e.length&&!i){const l=Cs.Color3toRGBAUint8(e);this.colorsTexture.update(l)}else(o=this.colorsTexture)==null||o.dispose(),this.colorsTexture=Cs.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){this._color===null&&e!==null||this._color!==null&&e===null?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var n;super.parse(e,t,i);const r=e.greasedLineMaterialOptions;(n=this.colorsTexture)==null||n.dispose(),r.color&&this.setColor(r.color,!0),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colors&&(this.colors=r.colors),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),this.colors?this.colorsTexture=Cs.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Cs.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var i;const t=e;(i=t.colorsTexture)==null||i.dispose(),this._colors&&(t.colorsTexture=Cs.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}f_.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";ve(`BABYLON.${f_.GREASED_LINE_MATERIAL_NAME}`,f_);const STt="greasedLinePixelShader",ETt=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} `;de.ShadersStore[STt]=ETt;const TTt="greasedLineVertexShader",MTt=`precision highp float; #include attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; #ifdef GREASED_LINE_CAMERA_FACING attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} #else attribute vec3 grl_slopes;attribute float grl_counters; #endif void main() { #include grlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ; #ifdef GREASED_LINE_CAMERA_FACING float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM grlNormal.xy*=-.5*grlWidth; #else grlNormal.xy*=.5*grlWidth; #endif grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; #else grlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; #endif } `;de.ShadersStore[TTt]=MTt;class o_e extends na{constructor(e,t,i){const r=["COLOR_DISTRIBUTION_TYPE_LINE 1.","COLOR_DISTRIBUTION_TYPE_SEGMENT 0.","COLOR_MODE_SET 0.","COLOR_MODE_ADD 1.","COLOR_MODE_MULTIPLY 2."],n=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&r.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(r.push("GREASED_LINE_CAMERA_FACING"),n.push("grl_previousAndSide","grl_nextAndCounters")):(n.push("grl_slopes"),n.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:n,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:r}),this._color=Re.White(),this._colorsDistributionType=0,this._colorsTexture=null,i=i||{color:Rl.DEFAULT_COLOR};const a=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?Rl.DEFAULT_WIDTH_ATTENUATED:Rl.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Re.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??yn.NEAREST_NEAREST,this.colorMode=i.colorMode??0,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new we(a.getRenderWidth(),a.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Cs.PrepareEmptyColorsTexture(t),this._colors&&this.useColors&&(this.colorsTexture=Cs.CreateColorsTexture(`${this.name}-colors-texture`,this._colors,this.colorsSampling,t)),a.onDisposeObservable.add(()=>{Cs.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)==null||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new we(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var n,a,o;const r=((n=this._colors)==null?void 0:n.length)??0;if(this._colors=e,e===null||e.length===0){(a=this._colorsTexture)==null||a.dispose();return}if(!(t&&!i))if(this._colorsTexture&&r===e.length&&!i){const l=Cs.Color3toRGBAUint8(e);this._colorsTexture.update(l)}else(o=this._colorsTexture)==null||o.dispose(),this.colorsTexture=Cs.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",Cs.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",Cs.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",Cs.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??Rl.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var n;const r=e.greasedLineMaterialOptions;(n=this._colorsTexture)==null||n.dispose(),r.color&&(this.color=r.color),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),r.colors?this.colorsTexture=Cs.CreateColorsTexture(`${this.name}-colors-texture`,r.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Cs.PrepareEmptyColorsTexture(t),this._cameraFacing=r.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}var ode;(function(s){s[s.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",s[s.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",s[s.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"})(ode||(ode={}));var lde;(function(s){s[s.COLOR_MODE_SET=0]="COLOR_MODE_SET",s[s.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",s[s.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"})(lde||(lde={}));var cde;(function(s){s[s.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",s[s.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"})(cde||(cde={}));const RTt=`#if defined(DBG_ENABLED) attribute float dbg_initialPass; varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; #endif`,ITt=`#if defined(DBG_ENABLED) attribute dbg_initialPass: f32; varying dbg_vBarycentric: vec3f; varying dbg_vVertexWorldPos: vec3f; varying dbg_vPass: f32; #endif`,PTt=`#if defined(DBG_ENABLED) float dbg_vertexIndex = mod(float(gl_VertexID), 3.); if (dbg_vertexIndex == 0.0) { dbg_vBarycentric = vec3(1.,0.,0.); } else if (dbg_vertexIndex == 1.0) { dbg_vBarycentric = vec3(0.,1.,0.); } else { dbg_vBarycentric = vec3(0.,0.,1.); } dbg_vVertexWorldPos = vPositionW; dbg_vPass = dbg_initialPass; #endif`,wTt=`#if defined(DBG_ENABLED) var dbg_vertexIndex = f32(input.vertexIndex) % 3.; if (dbg_vertexIndex == 0.0) { vertexOutputs.dbg_vBarycentric = vec3f(1.,0.,0.); } else if (dbg_vertexIndex == 1.0) { vertexOutputs.dbg_vBarycentric = vec3f(0.,1.,0.); } else { vertexOutputs.dbg_vBarycentric = vec3f(0.,0.,1.); } vertexOutputs.dbg_vVertexWorldPos = vertexOutputs.vPositionW; vertexOutputs.dbg_vPass = input.dbg_initialPass; #endif`,DTt=`#if defined(DBG_ENABLED) uniform vec3 dbg_shadedDiffuseColor; uniform vec4 dbg_shadedSpecularColorPower; uniform vec3 dbg_thicknessRadiusScale; #if DBG_MODE == 2 || DBG_MODE == 3 uniform vec3 dbg_vertexColor; #endif #if DBG_MODE == 1 uniform vec3 dbg_wireframeTrianglesColor; #elif DBG_MODE == 3 uniform vec3 dbg_wireframeVerticesColor; #elif DBG_MODE == 4 || DBG_MODE == 5 uniform vec3 dbg_uvPrimaryColor; uniform vec3 dbg_uvSecondaryColor; #elif DBG_MODE == 7 uniform vec3 dbg_materialColor; #endif #endif`,LTt=`#if defined(DBG_ENABLED) uniform dbg_shadedDiffuseColor: vec3f; uniform dbg_shadedSpecularColorPower: vec4f; uniform dbg_thicknessRadiusScale: vec3f; #if DBG_MODE == 2 || DBG_MODE == 3 uniform dbg_vertexColor: vec3f; #endif #if DBG_MODE == 1 uniform dbg_wireframeTrianglesColor: vec3f; #elif DBG_MODE == 3 uniform dbg_wireframeVerticesColor: vec3f; #elif DBG_MODE == 4 || DBG_MODE == 5 uniform dbg_uvPrimaryColor: vec3f; uniform dbg_uvSecondaryColor: vec3f; #elif DBG_MODE == 7 uniform dbg_materialColor: vec3f; #endif #endif`,OTt=`#if defined(DBG_ENABLED) varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; #if !defined(DBG_MULTIPLY) vec3 dbg_applyShading(vec3 color) { vec3 N = vNormalW.xyz; vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); vec3 H = normalize(L + L); float LdotN = clamp(dot(L,N), 0., 1.); float HdotN = clamp(dot(H,N), 0., 1.); float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); color *= (LdotN / PI); color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); return color; } #endif #if DBG_MODE == 1 || DBG_MODE == 3 float dbg_edgeFactor() { vec3 d = fwidth(dbg_vBarycentric); vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); return min(min(a3.x, a3.y), a3.z); } #endif #if DBG_MODE == 2 || DBG_MODE == 3 float dbg_cornerFactor() { vec3 worldPos = vPositionW; float dist = length(worldPos - dbg_vVertexWorldPos); float camDist = length(worldPos - vEyePosition.xyz); float d = sqrt(camDist) * .001; return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); } #endif #if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) float dbg_checkerboardFactor(vec2 uv) { vec2 f = fract(uv * dbg_thicknessRadiusScale.z); f -= .5; return (f.x * f.y) > 0. ? 1. : 0.; } #endif #endif`,NTt=`#if defined(DBG_ENABLED) varying dbg_vBarycentric: vec3f; varying dbg_vVertexWorldPos: vec3f; varying dbg_vPass: f32; #if !defined(DBG_MULTIPLY) fn dbg_applyShading(color: vec3f) -> vec3f { var N = fragmentInputs.vNormalW.xyz; var L = normalize(scene.vEyePosition.xyz - fragmentInputs.vPositionW.xyz); var H = normalize(L + L); var LdotN = clamp(dot(L,N), 0., 1.); var HdotN = clamp(dot(H,N), 0., 1.); var specTerm = pow(HdotN, uniforms.dbg_shadedSpecularColorPower.w); var result = color * (LdotN / PI); result += uniforms.dbg_shadedSpecularColorPower.rgb * (specTerm / PI); return result; } #endif #if DBG_MODE == 1 || DBG_MODE == 3 fn dbg_edgeFactor() -> f32 { var d = fwidth(fragmentInputs.dbg_vBarycentric); var a3 = smoothstep(vec3f(0.), d * uniforms.dbg_thicknessRadiusScale.x, fragmentInputs.dbg_vBarycentric); return min(min(a3.x, a3.y), a3.z); } #endif #if DBG_MODE == 2 || DBG_MODE == 3 fn dbg_cornerFactor() -> f32 { var worldPos = fragmentInputs.vPositionW; float dist = length(worldPos - fragmentInputs.dbg_vVertexWorldPos); float camDist = length(worldPos - scene.vEyePosition.xyz); float d = sqrt(camDist) * .001; return smoothstep((uniforms.dbg_thicknessRadiusScale.y * d), ((uniforms.dbg_thicknessRadiusScale.y * 1.01) * d), dist); } #endif #if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) fn dbg_checkerboardFactor(uv: vec2f) -> f32 { var f = fract(uv * uniforms.dbg_thicknessRadiusScale.z); f -= .5; return (f.x * f.y) > 0. ? 1. : 0.; } #endif #endif`,FTt=`#if defined(DBG_ENABLED) vec3 dbg_color = vec3(1.); #if DBG_MODE == 1 dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); #elif DBG_MODE == 2 || DBG_MODE == 3 float dbg_cornerFactor = dbg_cornerFactor(); if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); #if DBG_MODE == 3 dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); #endif #elif DBG_MODE == 4 && defined(MAINUV1) dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); #elif DBG_MODE == 5 && defined(MAINUV2) dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); #elif DBG_MODE == 6 && defined(VERTEXCOLOR) dbg_color = vColor.rgb; #elif DBG_MODE == 7 dbg_color = dbg_materialColor; #endif #if defined(DBG_MULTIPLY) gl_FragColor *= vec4(dbg_color, 1.); #else #if DBG_MODE != 6 gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); #else gl_FragColor = vec4(dbg_color, 1.); #endif #endif #endif`,BTt=`#if defined(DBG_ENABLED) var dbg_color = vec3f(1.); #if DBG_MODE == 1 dbg_color = mix(uniforms.dbg_wireframeTrianglesColor, vec3f(1.), dbg_edgeFactor()); #elif DBG_MODE == 2 || DBG_MODE == 3 var dbg_cornerFactor = dbg_cornerFactor(); if (fragmentInputs.dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; dbg_color = mix(uniforms.dbg_vertexColor, vec3(1.), dbg_cornerFactor); #if DBG_MODE == 3 dbg_color *= mix(uniforms.dbg_wireframeVerticesColor, vec3f(1.), dbg_edgeFactor()); #endif #elif DBG_MODE == 4 && defined(MAINUV1) dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV1)); #elif DBG_MODE == 5 && defined(MAINUV2) dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV2)); #elif DBG_MODE == 6 && defined(VERTEXCOLOR) dbg_color = fragmentInputs.vColor.rgb; #elif DBG_MODE == 7 dbg_color = uniforms.dbg_materialColor; #endif #if defined(DBG_MULTIPLY) fragmentOutputs.color *= vec4f(dbg_color, 1.); #else #if DBG_MODE != 6 fragmentOutputs.color = vec4f(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); #else fragmentOutputs.color = vec4f(dbg_color, 1.); #endif #endif #endif`,eje=[new Re(.98,.26,.38),new Re(.47,.75,.3),new Re(0,.26,.77),new Re(.97,.6,.76),new Re(.19,.63,.78),new Re(.98,.8,.6),new Re(.65,.43,.15),new Re(.15,.47,.22),new Re(.67,.71,.86),new Re(.09,.46,.56),new Re(.8,.98,.02),new Re(.39,.29,.13),new Re(.53,.63,.06),new Re(.95,.96,.41),new Re(1,.72,.94),new Re(.63,.08,.31),new Re(.66,.96,.95),new Re(.22,.14,.19),new Re(.14,.65,.59),new Re(.93,1,.68),new Re(.93,.14,.44),new Re(.47,.86,.67),new Re(.85,.07,.78),new Re(.53,.64,.98),new Re(.43,.37,.56),new Re(.71,.65,.25),new Re(.66,.19,.01),new Re(.94,.53,.12),new Re(.41,.44,.44),new Re(.24,.71,.96),new Re(.57,.28,.56),new Re(.44,.98,.42)];var ude;(function(s){s[s.NONE=0]="NONE",s[s.TRIANGLES=1]="TRIANGLES",s[s.VERTICES=2]="VERTICES",s[s.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",s[s.UV0=4]="UV0",s[s.UV1=5]="UV1",s[s.VERTEXCOLORS=6]="VERTEXCOLORS",s[s.MATERIALIDS=7]="MATERIALIDS"})(ude||(ude={}));class kTt extends _s{constructor(){super(...arguments),this.DBG_MODE=0,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class dl extends fu{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}isCompatible(e){switch(e){case 0:case 1:return!0;default:return!1}}constructor(e,t={}){const i=new kTt;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Re(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Re(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Re(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Re(.8,.8,.8),this.vertexColor=t.vertexColor??new Re(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Re(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Re(.5,.5,.5),this._materialColor=dl.MaterialColors[dl._PluginCount++%dl.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&this._material.getScene().getEngine().version==1){fe.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==2||this._mode==1||this._mode==3)&&!i.isVerticesDataPresent("dbg_initialPass")&&fe.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(e=0){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:e===0?DTt:LTt}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e,t=0){return t===1?e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:ITt,CUSTOM_VERTEX_MAIN_END:wTt}:{CUSTOM_FRAGMENT_DEFINITIONS:NTt,CUSTOM_FRAGMENT_MAIN_END:BTt}:e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:RTt,CUSTOM_VERTEX_MAIN_END:PTt}:{CUSTOM_FRAGMENT_DEFINITIONS:OTt,CUSTOM_FRAGMENT_MAIN_END:FTt}}static Reset(){this._PluginCount=0,this.MaterialColors=eje}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(e.getTotalIndices()==0)return i;if(t){const u=e.getVerticesDataKinds(),h=e.getIndices(),d={};for(const f of u)d[f]=e.getVerticesData(f);i=function(){e.setIndices(h);for(const f of u){const p=e.getVertexBuffer(f).getStrideSize();e.setVerticesData(f,d[f],void 0,p)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices());const n=[];for(let u=0;u #include #include varying vec4 vColor;varying vec2 vPosition;void main () { #include float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*vColor.a; #include vec3 color=vColor.rgb; #ifdef FOG #include #endif gl_FragColor=vec4(color,B);} `;de.ShadersStore[UTt]=zTt;const VTt="gaussianSplattingVertexDeclaration",GTt=`uniform mat4 world;uniform mat4 view;uniform mat4 projection; `;de.IncludesShadersStore[VTt]=GTt;const WTt="gaussianSplattingUboDeclaration",KTt=`#include #include `;de.IncludesShadersStore[WTt]=KTt;const HTt="gaussianSplattingVertexShader",jTt=`#include<__decl__gaussianSplattingVertex> #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include #include #include attribute vec2 position;attribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec4 vColor;varying vec2 vPosition; #if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE) mat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0], matrix[0][1],matrix[1][1],matrix[2][1], matrix[0][2],matrix[1][2],matrix[2][2]);} #endif vec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);} void main () {vec2 splatUV=getDataUV(splatIndex,dataTextureSize);vec3 center=texture2D(centersTexture,splatUV).xyz;vec4 color=texture2D(colorsTexture,splatUV);vec3 covA=texture2D(covariancesATexture,splatUV).xyz;vec3 covB=texture2D(covariancesBTexture,splatUV).xyz;vec4 worldPos=world*vec4(center,1.0);mat4 modelView=view*world;vec4 camspace=view*worldPos;vec4 pos2d=projection*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {gl_Position=vec4(0.0,0.0,2.0,1.0);return;} mat3 Vrk=mat3( covA.x,covA.y,covA.z, covA.y,covB.x,covB.y, covA.z,covB.y,covB.z );mat3 J=mat3( focal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z), 0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z), 0.,0.,0. );mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float lambda1=mid+radius,lambda2=mid-radius;if (lambda2<0.0) return;vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vColor=color;vPosition=position;vec2 vCenter=vec2(pos2d);gl_Position=vec4( vCenter + (position.x*majorAxis + position.y*minorAxis)*invViewport*pos2d.w,pos2d.zw); #include #include #include } `;de.ShadersStore[HTt]=jTt;class XTt extends _s{constructor(){super(),this.FOG=!1,this.THIN_INSTANCES=!0,this.LOGARITHMICDEPTH=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.rebuild()}}class uw extends aa{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===!0)return!0;t.materialDefines||(t.materialDefines=new XTt);const n=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(Kc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,a),Hc(n,o,this,a,!0,null,!0),Na(e,a,!1,!1),a.isDirty){a.markAsProcessed(),n.resetCachedMaterial();const l=[$.PositionKind,"splatIndex"];Ya(l,a);const c=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","invViewport","dataTextureSize","focal"],u=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],h=["Scene","Mesh"];po({uniformsNames:c,uniformBuffersNames:h,samplers:u,defines:a}),fo(c);const d=a.toString(),f=n.getEngine().createEffect("gaussianSplatting",{attributes:l,uniformsNames:c,uniformBuffersNames:h,samplers:u,defines:d,onCompiled:this.onCompiled,onError:this.onError},o);t.setEffect(f,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!0,!0)}bindForSubMesh(e,t,i){var l;const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;if(this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._mustRebind(r,a,i,t.visibility)){this.bindView(a),this.bindViewProjection(a);const c=r.getEngine(),u=this.getScene().activeCamera,h=c.getRenderWidth(),d=c.getRenderHeight(),f=((l=u==null?void 0:u.rigParent)==null?void 0:l.rigCameras.length)||1;this._activeEffect.setFloat2("invViewport",1/(h/f),1/d);let p=1e3;if(u){const g=u.getProjectionMatrix().m[5];u.fovMode==Nt.FOVMODE_VERTICAL_FIXED?p=d*g/2:p=h*g/2}this._activeEffect.setFloat2("focal",p,p);const m=t;if(m.covariancesATexture){const g=m.covariancesATexture.getSize();a.setFloat2("dataTextureSize",g.width,g.height),a.setTexture("covariancesATexture",m.covariancesATexture),a.setTexture("covariancesBTexture",m.covariancesBTexture),a.setTexture("centersTexture",m.centersTexture),a.setTexture("colorsTexture",m.colorsTexture)}Xa(a,this,r)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);ml(r,t,a),this.useLogarithmicDepth&&uo(n,a,r),this._afterBind(t,this._activeEffect,i)}clone(e){return qe.Clone(()=>new uw(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return qe.Parse(()=>new uw(e.name,t),e,t,i)}}ve("BABYLON.GaussianSplattingMaterial",uw);Object.defineProperty(et.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new aD(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(Pr.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new aD(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(Li.prototype,"decalMap",{get:function(){return this._decalMap},set:function(s){this._decalMap=s},enumerable:!0,configurable:!0});const YTt="defaultFragmentDeclaration",QTt=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; #ifdef SPECULARTERM uniform vec4 vSpecularColor; #endif uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; #ifdef DIFFUSE uniform vec2 vDiffuseInfos; #endif #ifdef AMBIENT uniform vec2 vAmbientInfos; #endif #ifdef OPACITY uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #ifdef ALPHATEST uniform float alphaCutOff; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) uniform mat4 view; #endif #ifdef REFRACTION uniform vec4 vRefractionInfos; #ifndef REFRACTIONMAP_3D uniform mat4 refractionMatrix; #endif #ifdef REFRACTIONFRESNEL uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; #endif #if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; #endif #endif #if defined(SPECULAR) && defined(SPECULARTERM) uniform vec2 vSpecularInfos; #endif #ifdef DIFFUSEFRESNEL uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; #endif #ifdef OPACITYFRESNEL uniform vec4 opacityParts; #endif #ifdef EMISSIVEFRESNEL uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; #endif #ifdef REFLECTION uniform vec2 vReflectionInfos; #if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) uniform mat4 reflectionMatrix; #endif #ifndef REFLECTIONMAP_SKYBOX #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif #ifdef REFLECTIONFRESNEL uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; #endif #endif #ifdef DETAIL uniform vec4 vDetailInfos; #endif #include #define ADDITIONAL_FRAGMENT_DECLARATION `;de.IncludesShadersStore[YTt]=QTt;const $Tt="defaultUboDeclaration",ZTt=`layout(std140,column_major) uniform;uniform Material {vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; #define ADDITIONAL_UBO_DECLARATION }; #include #include `;de.IncludesShadersStore[$Tt]=ZTt;const tje="defaultPixelShader",ije=`#include<__decl__defaultFragment> #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif #include[SCENE_MRT_COUNT] #include #define CUSTOM_FRAGMENT_BEGIN #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include[1..7] #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef REFRACTION #ifdef REFRACTIONMAP_3D uniform samplerCube refractionCubeSampler; #else uniform sampler2D refraction2DSampler; #endif #endif #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) #endif #include #ifdef REFLECTION #ifdef REFLECTIONMAP_3D uniform samplerCube reflectionCubeSampler; #else uniform sampler2D reflection2DSampler; #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #include #endif #include #include #include #include #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); #endif #include #ifdef TWOSIDEDLIGHTING normalW=gl_FrontFacing ? normalW : -normalW; #endif #ifdef DIFFUSE baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); #if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) baseColor.rgb*=vColor.rgb; #endif #ifdef DETAIL baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); #endif #if defined(DECAL) && defined(DECAL_AFTER_DETAIL) vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); #include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #define CUSTOM_FRAGMENT_UPDATE_DIFFUSE vec3 baseAmbientColor=vec3(1.,1.,1.); #ifdef AMBIENT baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; #endif #define CUSTOM_FRAGMENT_BEFORE_LIGHTS #ifdef SPECULARTERM float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; #ifdef SPECULAR vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; #ifdef GLOSSINESS glossiness=glossiness*specularMapColor.a; #endif #endif #else float glossiness=0.; #endif vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; #ifdef SPECULARTERM vec3 specularBase=vec3(0.,0.,0.); #endif float shadow=1.;float aggShadow=0.;float numLights=0.; #ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif #include[0..maxSimultaneousLights] aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); #ifdef REFRACTION vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); #ifdef REFRACTIONMAP_3D #ifdef USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); #endif refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} #else vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); #endif #ifdef RGBDREFRACTION refractionColor.rgb=fromRGBD(refractionColor); #endif #ifdef IS_REFRACTION_LINEAR refractionColor.rgb=toGammaSpace(refractionColor.rgb); #endif refractionColor.rgb*=vRefractionInfos.x; #endif vec4 reflectionColor=vec4(0.,0.,0.,1.); #ifdef REFLECTION vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #ifdef REFLECTIONMAP_OPPOSITEZ vReflectionUVW.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D #ifdef ROUGHNESS float bias=vReflectionInfos.y; #ifdef SPECULARTERM #ifdef SPECULAR #ifdef GLOSSINESS bias*=(1.0-specularMapColor.a); #endif #endif #endif reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); #else reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); #endif #else vec2 coords=vReflectionUVW.xy; #ifdef REFLECTIONMAP_PROJECTION coords/=vReflectionUVW.z; #endif coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); #endif #ifdef RGBDREFLECTION reflectionColor.rgb=fromRGBD(reflectionColor); #endif #ifdef IS_REFLECTION_LINEAR reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); #endif reflectionColor.rgb*=vReflectionInfos.x; #ifdef REFLECTIONFRESNEL float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); #ifdef REFLECTIONFRESNELFROMSPECULAR #ifdef SPECULARTERM reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #else reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #endif #else reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #endif #endif #endif #ifdef REFRACTIONFRESNEL float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); #ifdef OPACITYRGB opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; #else alpha*=opacityMap.a*vOpacityInfos.y; #endif #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=vColor.a; #endif #ifdef OPACITYFRESNEL float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; #endif #ifdef ALPHATEST #ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS if (alpha #include #ifdef IMAGEPROCESSINGPOSTPROCESS color.rgb=toLinearSpace(color.rgb); #else #ifdef IMAGEPROCESSING color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); #endif #endif color.a*=visibility; #ifdef PREMULTIPLYALPHA color.rgb*=color.a; #endif #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_IRRADIANCE gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_DEPTH gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); #else gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_ALBEDO_SQRT gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #if defined(SPECULARTERM) #if defined(SPECULAR) gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; #endif #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; #endif #endif #endif #if !defined(PREPASS) || defined(WEBGL2) gl_FragColor=color; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} #endif #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStore[tje]=ije;const rje={name:tje,shader:ije},qTt=Object.freeze(Object.defineProperty({__proto__:null,defaultPixelShader:rje},Symbol.toStringTag,{value:"Module"})),JTt="defaultVertexDeclaration",eMt=`uniform mat4 viewProjection;uniform mat4 view; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif #ifdef AMBIENT uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; #endif #ifdef OPACITY uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; #endif #if defined(SPECULAR) && defined(SPECULARTERM) uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; #endif #ifdef REFLECTION uniform mat4 reflectionMatrix; #endif #ifdef POINTSIZE uniform float pointSize; #endif #ifdef DETAIL uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION `;de.IncludesShadersStore[JTt]=eMt;const sje="defaultVertexShader",nje=`#include<__decl__defaultVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #ifdef TANGENT attribute vec4 tangent; #endif #ifdef UV1 attribute vec2 uv; #endif #include[2..7] #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #include #include[1..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #ifdef NORMAL vec3 normalUpdated=normal; #endif #ifdef TANGENT vec4 tangentUpdated=tangent; #endif #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normalUpdated); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif vPositionW=vec3(worldPos); #include #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); #endif #ifndef UV1 vec2 uvUpdated=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uvUpdated; #endif #include[2..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #include #include #include #include[0..maxSimultaneousLights] #include #include #include #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStore[sje]=nje;const aje={name:sje,shader:nje},tMt=Object.freeze(Object.defineProperty({__proto__:null,defaultVertexShader:aje},Symbol.toStringTag,{value:"Module"})),iMt="defaultUboDeclaration",rMt=`uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f; #define ADDITIONAL_UBO_DECLARATION #include #include `;de.IncludesShadersStoreWGSL[iMt]=rMt;const oje="defaultPixelShader",lje=`#include #include[SCENE_MRT_COUNT] #include #define CUSTOM_FRAGMENT_BEGIN varying vPositionW: vec3f; #ifdef NORMAL varying vNormalW: vec3f; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif #include[1..7] #include #include[0..maxSimultaneousLights] #include #include #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef REFRACTION #ifdef REFRACTIONMAP_3D var refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube; #else var refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d; #endif #endif #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) #endif #include #ifdef REFLECTION #ifdef REFLECTIONMAP_3D var reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube; #else var reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d; #endif #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #endif #include #endif #include #include #include #include #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a; #ifdef NORMAL var normalW: vec3f=normalize(fragmentInputs.vNormalW); #else var normalW: vec3f=normalize(-cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW))); #endif #include #ifdef TWOSIDEDLIGHTING normalW=select(-normalW,normalW,fragmentInputs.frontFacing); #endif #ifdef DIFFUSE baseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset); #if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) baseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a); #endif #ifdef DETAIL baseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a); #endif #if defined(DECAL) && defined(DECAL_AFTER_DETAIL) var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset); #include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #define CUSTOM_FRAGMENT_UPDATE_DIFFUSE var baseAmbientColor: vec3f= vec3f(1.,1.,1.); #ifdef AMBIENT baseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y; #endif #define CUSTOM_FRAGMENT_BEFORE_LIGHTS #ifdef SPECULARTERM var glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb; #ifdef SPECULAR var specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; #ifdef GLOSSINESS glossiness=glossiness*specularMapColor.a; #endif #endif #else var glossiness: f32=0.; #endif var diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo; #ifdef SPECULARTERM var specularBase: vec3f= vec3f(0.,0.,0.); #endif var shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.; #ifdef LIGHTMAP var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a); #endif lightmapColor=vec4f(lightmapColor.rgb*vLightmapInfos.y,lightmapColor.a); #endif #include[0..maxSimultaneousLights] aggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.); #ifdef REFRACTION var refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y)); #ifdef REFRACTIONMAP_3D #ifdef USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition); #endif refractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} #else var vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords); #endif #ifdef RGBDREFRACTION refractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a); #endif #ifdef IS_REFRACTION_LINEAR refractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a); #endif refractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a); #endif var reflectionColor: vec4f= vec4f(0.,0.,0.,1.); #ifdef REFLECTION var vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW); #ifdef REFLECTIONMAP_OPPOSITEZ vReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0); #endif #ifdef REFLECTIONMAP_3D #ifdef ROUGHNESS var bias: f32=uniforms.vReflectionInfos.y; #ifdef SPECULARTERM #ifdef SPECULAR #ifdef GLOSSINESS bias*=(1.0-specularMapColor.a); #endif #endif #endif reflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias); #else reflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW); #endif #else var coords: vec2f=vReflectionUVW.xy; #ifdef REFLECTIONMAP_PROJECTION coords/=vReflectionUVW.z; #endif coords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords); #endif #ifdef RGBDREFLECTION reflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a); #endif #ifdef IS_REFLECTION_LINEAR reflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a); #endif reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a); #ifdef REFLECTIONFRESNEL var reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a); #ifdef REFLECTIONFRESNELFROMSPECULAR #ifdef SPECULARTERM reflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); #else reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); #endif #else reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); #endif #endif #endif #ifdef REFRACTIONFRESNEL var refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a); #endif #ifdef OPACITY var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset); #ifdef OPACITYRGB opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y; #else alpha*=opacityMap.a*uniforms.vOpacityInfos.y; #endif #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=fragmentInputs.vColor.a; #endif #ifdef OPACITYFRESNEL var opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y; #endif #ifdef ALPHATEST #ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS if (alpha #include #ifdef IMAGEPROCESSINGPOSTPROCESS color=vec4f(toLinearSpaceVec3(color.rgb),color.a); #else #ifdef IMAGEPROCESSING color=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color); #endif #endif color=vec4f(color.rgb,color.a*mesh.visibility); #ifdef PREMULTIPLYALPHA color=vec4f(color.rgb*color.a, color.a); #endif #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS var writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array,SCENE_MRT_COUNT>;fragData[0]=color; #ifdef PREPASS_POSITION fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_IRRADIANCE fragData[PREPASS_IRRADIANCE_INDEX]= vec4f(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_DEPTH fragData[PREPASS_DEPTH_INDEX]= vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE fragData[PREPASS_NORMAL_INDEX]= vec4f(normalW,writeGeometryInfo); #else fragData[PREPASS_NORMAL_INDEX]= vec4f(normalize((scene.view* vec4f(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_ALBEDO_SQRT fragData[PREPASS_ALBEDO_SQRT_INDEX]= vec4f(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #if defined(SPECULARTERM) #if defined(SPECULAR) fragData[PREPASS_REFLECTIVITY_INDEX]= vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo; #else fragData[PREPASS_REFLECTIVITY_INDEX]= vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo; #endif #else fragData[PREPASS_REFLECTIVITY_INDEX]= vec4f(0.0,0.0,0.0,1.0)*writeGeometryInfo; #endif #endif #if SCENE_MRT_COUNT>0 fragmentOutputs.fragData0= fragData[0]; #endif #if SCENE_MRT_COUNT>1 fragmentOutputs.fragData1= fragData[1]; #endif #if SCENE_MRT_COUNT>2 fragmentOutputs.fragData2= fragData[2]; #endif #if SCENE_MRT_COUNT>3 fragmentOutputs.fragData3= fragData[3]; #endif #if SCENE_MRT_COUNT>4 fragmentOutputs.fragData4= fragData[4]; #endif #if SCENE_MRT_COUNT>5 fragmentOutputs.fragData5= fragData[5]; #endif #if SCENE_MRT_COUNT>6 fragmentOutputs.fragData6= fragData[6]; #endif #if SCENE_MRT_COUNT>7 fragmentOutputs.fragData7= fragData[7]; #endif #endif #if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) fragmentOutputs.color=color; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;} #endif #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStoreWGSL[oje]=lje;const cje={name:oje,shader:lje},sMt=Object.freeze(Object.defineProperty({__proto__:null,defaultPixelShaderWGSL:cje},Symbol.toStringTag,{value:"Module"})),nMt="lightVxFragmentDeclaration",aMt=`#ifdef LIGHT{X} uniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f; #ifdef SPECULARTERM uniform vLightSpecular{X}: vec4f; #else var vLightSpecular{X}: vec4f= vec4f(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f; #elif defined(SHADOWCUBE{X}) #else varying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f; #endif uniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f; #endif #ifdef SPOTLIGHT{X} uniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f; #elif defined(POINTLIGHT{X}) uniform vLightFalloff{X}: vec4f; #elif defined(HEMILIGHT{X}) uniform vLightGround{X}: vec3f; #endif #endif `;de.IncludesShadersStoreWGSL[nMt]=aMt;const uje="defaultVertexShader",hje=`#include #define CUSTOM_VERTEX_BEGIN attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif #ifdef TANGENT attribute tangent: vec4f; #endif #ifdef UV1 attribute uv: vec2f; #endif #include[2..7] #ifdef VERTEXCOLOR attribute color: vec4f; #endif #include #include #include #include #include #include[1..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) varying vPositionW: vec3f; #ifdef NORMAL varying vNormalW: vec3f; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var positionUpdated: vec3f=vertexInputs.position; #ifdef NORMAL var normalUpdated: vec3f=vertexInputs.normal; #endif #ifdef TANGENT var tangentUpdated: vec4f=vertexInputs.tangent; #endif #ifdef UV1 var uvUpdated: vec2f=vertexInputs.uv; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vertexOutputs.vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #include #include var worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0); #ifdef NORMAL var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); #if defined(INSTANCES) && defined(THIN_INSTANCES) vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;} #else vertexOutputs.position=scene.viewProjection*worldPos; #endif vertexOutputs.vPositionW= worldPos.xyz; #include #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz); #endif #ifndef UV1 var uvUpdated: vec2f=vec2f(0.,0.); #endif #ifdef MAINUV1 vertexOutputs.vMainUV1=uvUpdated; #endif #include[2..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #include #include #include #include[0..maxSimultaneousLights] #include #include #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStoreWGSL[uje]=hje;const dje={name:uje,shader:hje},oMt=Object.freeze(Object.defineProperty({__proto__:null,defaultVertexShaderWGSL:dje},Symbol.toStringTag,{value:"Module"}));let lMt=class Cm{constructor(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new Cm(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new Cm(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new Cm(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new Cm(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new Cm(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Cm(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new Cm(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new we(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new Cm(0,0);return Cm.FromVector2ToRef(e,t),t}static FromArray(e){return new Cm(e[0],e[1])}};class Hp{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new Hp(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new Hp(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,r){return r.radius=this.radius-e,r.theta=this.theta-t,r.phi=this.phi-i,r}subtractFromFloats(e,t,i){const r=new Hp(0,0,0);return this.subtractFromFloatsToRef(e,t,i,r),r}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new Hp(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new Hp(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Hp(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new Hp(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),r=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,r),e}toVector3(){const e=new D(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new Hp(0,0,0);return Hp.FromVector3ToRef(e,t),t}static FromArray(e){return new Hp(e[0],e[1],e[2])}}class fje{constructor(e,t=2,i=3,r=1,n=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=r,this._height=n,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=this._numSamples*2&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,r=0;for(;e>0;)i/=t,r+=i*(e%t),e=~~(e/t);return r}}function pje(s,e){return`{X: ${s.x.toFixed(e)} Y: ${s.y.toFixed(e)}}`}function mje(s,e){return`{X: ${s._x.toFixed(e)} Y: ${s._y.toFixed(e)} Z: ${s._z.toFixed(e)}}`}function gje(s,e){return`{X: ${s.x.toFixed(e)} Y: ${s.y.toFixed(e)} Z: ${s.z.toFixed(e)} W: ${s.w.toFixed(e)}}`}function hde(s,e,t,i,r){let n=null,a=null,o=null;try{n=new s.Decoder,a=new s.DecoderBuffer,a.Init(e,e.byteLength);let l;const c=n.GetEncodedGeometryType(a);switch(c){case s.TRIANGULAR_MESH:{const d=new s.Mesh;if(l=n.DecodeBufferToMesh(a,d),!l.ok()||d.ptr===0)throw new Error(l.error_msg());const p=d.num_faces()*3,m=p*4,g=s._malloc(m);try{n.GetTrianglesUInt32Array(d,m,g);const _=new Uint32Array(p);_.set(new Uint32Array(s.HEAPF32.buffer,g,p)),i(_)}finally{s._free(g)}o=d;break}case s.POINT_CLOUD:{const d=new s.PointCloud;if(l=n.DecodeBufferToPointCloud(a,d),!l.ok()||!d.ptr)throw new Error(l.error_msg());o=d;break}default:throw new Error(`Invalid geometry type ${c}`)}const u=o.num_points(),h=(d,f,p,m)=>{const g=m.data_type(),_=m.num_components(),y=m.normalized(),v=m.byte_stride(),x=m.byte_offset(),b={[s.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:s.HEAPF32},[s.DT_INT8]:{typedArrayConstructor:Int8Array,heap:s.HEAP8},[s.DT_INT16]:{typedArrayConstructor:Int16Array,heap:s.HEAP16},[s.DT_INT32]:{typedArrayConstructor:Int32Array,heap:s.HEAP32},[s.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:s.HEAPU8},[s.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:s.HEAPU16},[s.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:s.HEAPU32}}[g];if(!b)throw new Error(`Invalid data type ${g}`);const C=u*_,T=C*b.typedArrayConstructor.BYTES_PER_ELEMENT,w=s._malloc(T);try{d.GetAttributeDataArrayForAllPoints(f,m,g,T,w);const P=new b.typedArrayConstructor(b.heap.buffer,w,C);r(p,P.slice(),_,x,v,y)}finally{s._free(w)}};if(t)for(const d in t){const f=t[d],p=n.GetAttributeByUniqueId(o,f);h(n,o,d,p)}else{const d={position:s.POSITION,normal:s.NORMAL,color:s.COLOR,uv:s.TEX_COORD};for(const f in d){const p=n.GetAttributeId(o,d[f]);if(p!==-1){const m=n.GetAttribute(o,p);h(n,o,f,m)}}}return u}finally{o&&s.destroy(o),a&&s.destroy(a),n&&s.destroy(n)}}function cMt(){let s;onmessage=e=>{const t=e.data;switch(t.id){case"init":{const i=t.decoder;i.url&&importScripts(i.url);const r=i.wasmBinary?{wasmBinary:i.wasmBinary}:{};s=DracoDecoderModule(r),postMessage({id:"initDone"});break}case"decodeMesh":{if(!s)throw new Error("Draco decoder module is not available");s.then(i=>{const r=hde(i,t.dataView,t.attributes,n=>{postMessage({id:"indices",data:n},[n.buffer])},(n,a,o,l,c,u)=>{postMessage({id:"attribute",kind:n,data:a,size:o,byteOffset:l,byteStride:c,normalized:u},[a.buffer])});postMessage({id:"decodeMeshDone",totalVertices:r})});break}}}}function uMt(s,e,t){return new Promise((i,r)=>{const n=o=>{s.removeEventListener("error",n),s.removeEventListener("message",a),r(o)},a=o=>{o.data.id==="initDone"&&(s.removeEventListener("error",n),s.removeEventListener("message",a),i(s))};if(s.addEventListener("error",n),s.addEventListener("message",a),!e)s.postMessage({id:"init",decoder:{url:t}});else{const o=e.slice(0);s.postMessage({id:"init",decoder:{url:t,wasmBinary:o}},[o])}})}function hMt(s,e){return new Promise(t=>{(e||DracoDecoderModule)({wasmBinary:s}).then(i=>{t({module:i})})})}class Kl{static get DecoderAvailable(){const e=Kl.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&typeof WebAssembly=="object"||e.fallbackUrl)}static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static get Default(){return Kl._Default||(Kl._Default=new Kl),Kl._Default}static ResetDefault(e){Kl._Default&&(e||Kl._Default.dispose(),Kl._Default=null)}constructor(e=Kl.DefaultNumWorkers){const t=Kl.Configuration.decoder;if(t.workerPool||typeof e=="object"&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||typeof e=="object"&&e.wasmBinary,r=typeof e=="number"?e:e.numWorkers,n=r&&typeof Worker=="function"&&typeof URL=="function",a=n||!n&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:a?Me.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Me.LoadFileAsync(Me.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:a?Me.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};n?this._workerPoolPromise=o.wasmBinaryPromise.then(l=>{const c=`${hde}(${cMt})()`,u=URL.createObjectURL(new Blob([c],{type:"application/javascript"}));return new rD(r,()=>{const h=new Worker(u);return uMt(h,l,o.url)})}):this._decoderModulePromise=o.wasmBinaryPromise.then(async l=>{if(typeof DracoDecoderModule>"u"&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Me.LoadBabylonScriptAsync(o.url)}return await hMt(l,t.jsModule)})}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){if(this._workerPoolPromise){await this._workerPoolPromise;return}if(this._decoderModulePromise){await this._decoderModulePromise;return}}decodeMeshToMeshDataAsync(e,t,i){const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),n=(a,o)=>i&&i[a]!==void 0?(o!==i[a]&&fe.Warn(`Normalized flag from Draco data (${o}) does not match normalized flag from glTF accessor (${i[a]}). Using flag from glTF accessor.`),i[a]):o;if(this._workerPoolPromise)return this._workerPoolPromise.then(a=>new Promise((o,l)=>{a.push((c,u)=>{let h=null;const d=[],f=g=>{c.removeEventListener("error",f),c.removeEventListener("message",p),l(g),u()},p=g=>{const _=g.data;switch(_.id){case"decodeMeshDone":{c.removeEventListener("error",f),c.removeEventListener("message",p),o({indices:h,attributes:d,totalVertices:_.totalVertices}),u();break}case"indices":{h=_.data;break}case"attribute":{d.push({kind:_.kind,data:_.data,size:_.size,byteOffset:_.byteOffset,byteStride:_.byteStride,normalized:n(_.kind,_.normalized)});break}}};c.addEventListener("error",f),c.addEventListener("message",p);const m=r.slice();c.postMessage({id:"decodeMesh",dataView:m,attributes:t},[m.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(a=>{let o=null;const l=[],c=hde(a.module,r,t,u=>{o=u},(u,h,d,f,p,m)=>{l.push({kind:u,data:h,size:d,byteOffset:f,byteStride:p,normalized:m})});return{indices:o,attributes:l,totalVertices:c}});throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,r){const n=await this.decodeMeshToMeshDataAsync(i,r),a=new So(e,t);n.indices&&a.setIndices(n.indices);for(const o of n.attributes)a.setVerticesBuffer(new $(t.getEngine(),o.data,o.kind,!1,void 0,o.byteStride,void 0,o.byteOffset,o.size,void 0,o.normalized,!0),n.totalVertices);return a}async _decodeMeshToGeometryForGltfAsync(e,t,i,r,n){const a=await this.decodeMeshToMeshDataAsync(i,r,n),o=new So(e,t);a.indices&&o.setIndices(a.indices);for(const l of a.attributes)o.setVerticesBuffer(new $(t.getEngine(),l.data,l.kind,!1,void 0,l.byteStride,void 0,l.byteOffset,l.size,void 0,l.normalized,!0),a.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),r=new at;i.indices&&(r.indices=i.indices);for(const n of i.attributes){const a=$.GetFloatData(n.data,n.size,$.GetDataType(n.data),n.byteOffset,n.byteStride,n.normalized,i.totalVertices);r.set(a,n.kind)}return r}}Kl.Configuration={decoder:{wasmUrl:`${Me._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Me._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Me._DefaultCdnUrl}/draco_decoder_gltf.js`}};Kl.DefaultNumWorkers=Kl.GetDefaultNumWorkers();Kl._Default=null;class N1{static get Default(){return N1._Default||(N1._Default=new N1),N1._Default}constructor(){const e=N1.Configuration.decoder;this._decoderModulePromise=Me.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,n){return this._decoderModulePromise.then(async()=>{MeshoptDecoder.useWorkers(1);const a=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,r,n);return MeshoptDecoder.useWorkers(0),a})}}N1.Configuration={decoder:{url:`${Me._DefaultCdnUrl}/meshopt_decoder.js`}};N1._Default=null;let pY=0;class Yk{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new Yk(this.pos.clone(),this.normal.clone(),(e=this.uv)==null?void 0:e.clone(),(t=this.vertColor)==null?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Yk(D.Lerp(this.pos,e.pos,t),D.Lerp(this.normal,e.normal,t),this.uv&&e.uv?we.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Ze.Lerp(this.vertColor,e.vertColor,t):void 0)}}class cS{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const r=i.subtract(e),n=t.subtract(e);if(r.lengthSquared()===0||n.lengthSquared()===0)return null;const a=D.Normalize(D.Cross(r,n));return new cS(a,D.Dot(a,e))}clone(){return new cS(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,n){let u=0;const h=[];let d,f;for(d=0;dcS.EPSILON?1:0;u|=p,h.push(p)}switch(u){case 0:(D.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:n.push(e);break;case 3:{const p=[],m=[];for(d=0;d=3&&(g=new hw(p,e.shared),g.plane&&r.push(g)),m.length>=3&&(g=new hw(m,e.shared),g.plane&&n.push(g));break}}}}cS.EPSILON=1e-5;class hw{constructor(e,t){this.vertices=e,this.shared=t,this.plane=cS.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new hw(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let Bp=class $Q{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new $Q;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(t=>t.clone()),e}invert(){for(let t=0;tt.clone()),e.copyTransformAttributes(this),e}union(e){const t=new Bp(this.clone()._polygons),i=new Bp(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Om._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new Bp(this._polygons),i=new Bp(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new Bp(this.clone()._polygons),i=new Bp(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),Om._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new Bp(this._polygons),i=new Bp(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new Bp(this.clone()._polygons),i=new Bp(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Om._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new Bp(this._polygons),i=new Bp(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const r=this._polygons,n=[],a=[],o=[];let l=null,c=null;const u=D.Zero(),h=D.Zero(),d=we.Zero(),f=new Ze(0,0,0,0),p=[0,0,0],m={};let g;for(let y=0,v=r.length;yu.shared.meshId===h.shared.meshId?u.shared.subMeshId-h.shared.subMeshId:u.shared.meshId-h.shared.meshId),this.toVertexData(u=>{o[u.shared.meshId]||(o[u.shared.meshId]={}),o[u.shared.meshId][u.shared.subMeshId]||(o[u.shared.meshId][u.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:u.shared.materialIndex}),l=o[u.shared.meshId][u.shared.subMeshId]},()=>{l.indexStart=Math.min(a,l.indexStart),l.indexEnd=Math.max(a,l.indexEnd),a++}).applyToMesh(r),i){let u=0,h;r.subMeshes=[];for(const d in o){h=-1;for(const f in o[d])l=o[d][f],wl.CreateFromIndices(l.materialIndex+u,l.indexStart,l.indexEnd-l.indexStart+1,r),h=Math.max(l.materialIndex,h);u+=++h}}return r}toMesh(e,t=null,i,r){const n=this.buildMeshGeometry(e,i,r);return n.material=t,n.position.copyFrom(this.position),n.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(n.rotationQuaternion=this.rotationQuaternion.clone()),n.scaling.copyFrom(this.scaling),n.computeWorldMatrix(!0),n}}class y1{static _GetShader(e,t){if(!e._meshUVSpaceRendererShader){const i=new na("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0,shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add(()=>{var r;(r=e._meshUVSpaceRendererShader)==null||r.dispose(),e._meshUVSpaceRendererShader=null}),e._meshUVSpaceRendererShader=i}return e._meshUVSpaceRendererShader}static _GetMaskShader(e,t){if(!e._meshUVSpaceRendererMaskShader){const i=new na("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"],shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add(()=>{var r;(r=e._meshUVSpaceRendererMaskShader)==null||r.dispose(),e._meshUVSpaceRendererMaskShader=null}),e._meshUVSpaceRendererMaskShader=i}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return e.renderList!==void 0}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this._shadersLoaded=!1,this.clearColor=new Ze(0,0,0,0),this._shaderLanguage=0,this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i},this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU?(this._shaderLanguage=1,await Promise.all([Ue(()=>Promise.resolve().then(()=>TMt),void 0),Ue(()=>Promise.resolve().then(()=>MMt),void 0),Ue(()=>Promise.resolve().then(()=>RMt),void 0),Ue(()=>Promise.resolve().then(()=>IMt),void 0),Ue(()=>Promise.resolve().then(()=>wMt),void 0),Ue(()=>Promise.resolve().then(()=>PMt),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>xMt),void 0),Ue(()=>Promise.resolve().then(()=>AMt),void 0),Ue(()=>Promise.resolve().then(()=>bMt),void 0),Ue(()=>Promise.resolve().then(()=>CMt),void 0),Ue(()=>Promise.resolve().then(()=>EMt),void 0),Ue(()=>Promise.resolve().then(()=>SMt),void 0)]),this._shadersLoaded=!0,this._createDiffuseRTT()}isReady(){var r,n;if(!this._shadersLoaded)return!1;this.texture||this._createDiffuseRTT();const e=y1._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=((r=this._maskTexture)==null?void 0:r.isReadyForRendering())??!0,i=((n=this._finalPostProcess)==null?void 0:n.isReady())??!0;return e&&t&&i}renderTexture(e,t,i,r,n=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),y1._IsRenderTargetTexture(this.texture)){const a=this._createProjectionMatrix(t,i,r,n),o=y1._GetShader(this._scene,this._shaderLanguage);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",a),this.texture.render()}}clear(){var e,t,i;if(y1._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const r=this._scene.getEngine();r.bindFramebuffer(this.texture.renderTarget),r.clear(this.clearColor,!0,!0,!0),r.unBindFramebuffer(this.texture.renderTarget)}if((e=this._finalPostProcess)!=null&&e.inputTexture){const r=this._scene.getEngine();r.bindFramebuffer((t=this._finalPostProcess)==null?void 0:t.inputTexture),r.clear(this.clearColor,!0,!0,!0),r.unBindFramebuffer((i=this._finalPostProcess)==null?void 0:i.inputTexture)}}dispose(){var e,t;this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,(e=this._maskTexture)==null||e.dispose(),this._maskTexture=null,(t=this._finalPostProcess)==null||t.dispose(),this._finalPostProcess=null}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,y1._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,y1._GetShader(this._scene,this._shaderLanguage)),this.texture.onClearObservable.add(()=>{}),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,y1._GetShader(this._scene,this._shaderLanguage)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new Rs(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new Ze(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,y1._GetMaskShader(this._scene,this._shaderLanguage)),this._maskTexture.refreshRate=Rs.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new Ft(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._finalPostProcess.onApplyObservable.add(e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)}))}_createRenderTargetTexture(e,t){const i=new Rs(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce(()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add(()=>{})}),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,r=0){const n=-Math.atan2(t.z,t.x)-Math.PI/2,a=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,a),l=e.add(t.scale(i.z*.5)),c=he.RotationYawPitchRoll(n,o,r).multiply(he.Translation(l.x,l.y,l.z)),u=he.Invert(c),h=he.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),d=he.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return u.multiply(h).multiply(d)}}Ee._TrailMeshParser=(s,e)=>Qk.Parse(s,e);class Qk extends Ee{constructor(e,t,i,r,n=60,a=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,typeof r=="object"&&r!==null?(this.diameter=r.diameter||1,this._length=r.length||60,this._segments=r.segments?r.segments>this._length?this._length:r.segments:this._length,this._sectionPolygonPointsCount=r.sections||4,this._doNotTaper=r.doNotTaper||!1,this._autoStart=r.autoStart||!0):(this.diameter=r||1,this._length=n,this._segments=this._length,this._doNotTaper=!1,this._autoStart=a),this._sectionVectors=[],this._sectionNormalVectors=[];for(let o=0;o<=this._sectionPolygonPointsCount;o++)this._sectionVectors[o]=D.Zero(),this._sectionNormalVectors[o]=D.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new at,t=[],i=[],r=[],n=[];let a=D.Zero();this._generator instanceof Li&&this._generator.hasBoundingInfo?a=this._generator.getBoundingInfo().boundingBox.centerWorld:a=this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let l=0;l<=this._sectionPolygonPointsCount;l++){const c=l!==this._sectionPolygonPointsCount?l*o:0;t.push(a.x+Math.cos(c)*this.diameter,a.y+Math.sin(c)*this.diameter,a.z),n.push(l/this._sectionPolygonPointsCount,0)}for(let l=1;l<=this._segments;l++){for(let u=0;u<=this._sectionPolygonPointsCount;u++){const h=u!==this._sectionPolygonPointsCount?u*o:0;t.push(a.x+Math.cos(h)*this.diameter,a.y+Math.sin(h)*this.diameter,a.z),n.push(u/this._sectionPolygonPointsCount,l/this._segments)}const c=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let u=0;u<=this._sectionPolygonPointsCount;u++)r.push(c+u,c+u+this._sectionPolygonPointsCount,c+u+this._sectionPolygonPointsCount+1),r.push(c+u,c+u+this._sectionPolygonPointsCount+1,c+u+1)}at.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.uvs=n,e.applyToMesh(this,!0),this._autoStart&&this.start()}_updateSectionVectors(){const e=this._generator.getWorldMatrix(),t=2*Math.PI/this._sectionPolygonPointsCount;for(let i=0;i<=this._sectionPolygonPointsCount;i++){const r=i!==this._sectionPolygonPointsCount?i*t:0;this._sectionVectors[i].copyFromFloats(Math.cos(r)*this.diameter,Math.sin(r)*this.diameter,0),this._sectionNormalVectors[i].copyFromFloats(Math.cos(r),Math.sin(r),0),D.TransformCoordinatesToRef(this._sectionVectors[i],e,this._sectionVectors[i]),D.TransformNormalToRef(this._sectionNormalVectors[i],e,this._sectionNormalVectors[i])}}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(()=>{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData($.PositionKind),t=this.getVerticesData($.NormalKind),i=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let n=i;n{this._getSimplifier(e).simplify(t,r=>{t.distance!==void 0&&e.mesh.addLODLevel(t.distance,r),r.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{const t=this._getSimplifier(e),i=(r,n)=>{t.simplify(r,a=>{r.distance!==void 0&&e.mesh.addLODLevel(r.distance,a),a.isVisible=!0,n()})};Of.Run(e.settings.length,r=>{i(e.settings[r.index],()=>{r.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case 0:default:return new vje(e.mesh)}}}var dde;(function(s){s[s.QUADRATIC=0]="QUADRATIC"})(dde||(dde={}));class fMt{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class pMt{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new hP,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class hP{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,n,a,o,l,c){return this.data[e]*this.data[n]*this.data[c]+this.data[i]*this.data[r]*this.data[l]+this.data[t]*this.data[a]*this.data[o]-this.data[i]*this.data[n]*this.data[o]-this.data[e]*this.data[a]*this.data[l]-this.data[t]*this.data[r]*this.data[c]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new hP;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new hP(hP.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class mMt{constructor(e,t){this.vertexId=e,this.triangleId=t}}class vje{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=ci}simplify(e,t){this._initDecimatedMesh(),Of.Run(this._mesh.subMeshes.length,i=>{this._initWithMesh(i.index,()=>{this._runDecimation(e,i.index,()=>{i.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){const r=~~(this._triangles.length*e.quality);let n=0;const a=this._triangles.length,o=(l,c)=>{setTimeout(()=>{l%5===0&&this._updateMesh(l===0);for(let d=0;d{const f=~~((this._triangles.length/2+d)%this._triangles.length),p=this._triangles[f];if(p&&!(p.error[3]>u||p.deleted||p.isDirty)){for(let m=0;m<3;++m)if(p.error[m]{b.indexOf(w)===-1&&(w.deletePending=!0,b.push(w))}),b.length%2!==0)continue;y.q=v.q.add(y.q),y.updatePosition(x);const C=this._references.length;n=this._updateTriangles(y,y,g,n),n=this._updateTriangles(y,v,_,n);const T=this._references.length-C;if(T<=y.triangleCount){if(T)for(let w=0;wa-n<=r)},0)};Of.Run(this.decimationIterations,l=>{a-n<=r?l.breakLoop():o(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const r=this._mesh.getVerticesData($.PositionKind),n=this._mesh.getIndices(),a=this._mesh.subMeshes[e],o=h=>{if(i){for(let d=0;d{if(!r)return;const d=h+a.verticesStart,f=D.FromArray(r,d*3),p=o(f)||new pMt(f,this._vertices.length);p.originalOffsets.push(d),p.id===this._vertices.length&&this._vertices.push(p),l.push(p.id)},u=a.verticesCount;Of.SyncAsyncForLoop(u,this.syncIterations/4>>0,c,()=>{const h=d=>{if(!n)return;const p=(a.indexStart/3+d)*3,m=n[p+0],g=n[p+1],_=n[p+2],y=this._vertices[l[m-a.verticesStart]],v=this._vertices[l[g-a.verticesStart]],x=this._vertices[l[_-a.verticesStart]],A=new fMt([y,v,x]);A.originalOffset=p,this._triangles.push(A)};Of.SyncAsyncForLoop(a.indexCount/3,this.syncIterations,h,()=>{this._init(t)})})}_init(e){const t=i=>{const r=this._triangles[i];r.normal=D.Cross(r._vertices[1].position.subtract(r._vertices[0].position),r._vertices[2].position.subtract(r._vertices[0].position)).normalize();for(let n=0;n<3;n++)r._vertices[n].q.addArrayInPlace(hP.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-D.Dot(r.normal,r._vertices[0].position)))};Of.SyncAsyncForLoop(this._triangles.length,this.syncIterations,t,()=>{const i=r=>{const n=this._triangles[r];for(let a=0;a<3;++a)n.error[a]=this._calculateError(n._vertices[a],n._vertices[(a+1)%3]);n.error[3]=Math.min(n.error[0],n.error[1],n.error[2])};Of.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i{a.push(x.position.x),a.push(x.position.y),a.push(x.position.z),u&&u.length&&(o.push(u[A*3]),o.push(u[A*3+1]),o.push(u[A*3+2])),h&&h.length&&(l.push(h[A*2]),l.push(h[A*2+1])),d&&d.length&&(c.push(d[A*4]),c.push(d[A*4+1]),c.push(d[A*4+2]),c.push(d[A*4+3])),++f})}const p=this._reconstructedMesh.getTotalIndices(),m=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const _=this._reconstructedMesh.getIndices(),y=this._mesh.getIndices();for(i=0;i{const A=y[r.originalOffset+x];let b=r._vertices[x].originalOffsets.indexOf(A);b<0&&(b=0),_.push(r._vertices[x].id+b+m)});this._reconstructedMesh.setIndices(_),this._reconstructedMesh.setVerticesData($.PositionKind,a),o.length>0&&this._reconstructedMesh.setVerticesData($.NormalKind,o),l.length>0&&this._reconstructedMesh.setVerticesData($.UVKind,l),c.length>0&&this._reconstructedMesh.setVerticesData($.ColorKind,c);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],g.forEach(x=>{wl.AddToMesh(x.materialIndex,x.verticesStart,x.verticesCount,x.indexStart,x.indexCount,x.getMesh())}),wl.AddToMesh(v.materialIndex,m,f,p,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Ee(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,n){for(let a=0;a.999)return!0;const f=D.Cross(h,d).normalize();if(r[a]=!1,D.Dot(f,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,r){let n=r;for(let a=0;aMath.max(f,p.getTotalVertices()),0),o=Array.from({length:a},()=>new D),l=Array.from({length:a},()=>new D);for(const f of s){const p=f.getVerticesData($.PositionKind);if(!p)continue;const m=f.getTotalVertices();o.length=Math.max(o.length,m),l.length=Math.max(o.length,m);for(let x=0,A=0;x4,A=x?f.getVerticesData($.MatricesWeightsExtraKind):null,b=x?f.getVerticesData($.MatricesIndicesExtraKind):null,C=n.get(f.uniqueId)||new Map;n.set(f.uniqueId,C);const T=(w,P,M,R)=>{for(let I=P;I0){const L=R[I],k=C.get(L);k?(k.minimum.minimizeInPlace(o[w]),k.maximum.maximizeInPlace(l[w])):C.set(L,{minimum:o[w].clone(),maximum:l[w].clone()})}};for(let w=0,P=0;w{const x=fMe(y),A=g[v].getAbsoluteInverseBindMatrix();for(const b of x)D.TransformCoordinatesToRef(b,A,b);_.set(v,x)})}}}const h=Array.from({length:s.length},()=>({minimum:new D().setAll(Number.POSITIVE_INFINITY),maximum:new D().setAll(Number.NEGATIVE_INFINITY)})),d=()=>{for(let f=0;f{for(const A of v){const b=_[x].getFinalMatrix().multiplyToRef(m,se.Matrix[0]);D.TransformCoordinatesToRef(A,b,i),h[f].minimum.minimizeInPlace(i),h[f].maximum.maximizeInPlace(i)}})}else for(const _ of c.get(p.uniqueId))D.TransformCoordinatesToRef(_,m,i),h[f].minimum.minimizeInPlace(i),h[f].maximum.maximizeInPlace(i)}};if(e&&e.isStarted){const f=t/e.getLength(0,1);for(let p=e.from;p<=e.to;p+=f)e.goToFrame(p),d()}else d();return h}var fde;(function(s){s[s.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",s[s.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"})(fde||(fde={}));var pde;(function(s){s[s.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",s[s.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",s[s.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"})(pde||(pde={}));var mde;(function(s){s[s.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",s[s.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",s[s.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",s[s.AUTO_DIRECTIONS_FACE_TO=3]="AUTO_DIRECTIONS_FACE_TO",s[s.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"})(mde||(mde={}));class l_e extends Ee{constructor(e,t,i){super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this._engine=t.getEngine(),this._lazy=i.lazy??!1,this._updatable=i.updatable??!1,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=i.colorPointers??[],this._widths=i.widths??new Array(i.points.length).fill(1)}getClassName(){return"GreasedLineMesh"}_updateWidthsWithValue(e){let t=0;for(const r of this._points)t+=r.length;const i=t/3*2-this._widths.length;for(let r=0;rbl.Parse(s,e);class bl extends l_e{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Cs.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{i+=_.length*2,r+=(_.length-3)*2,n+=_.length*4/3,a+=_.length*8/3});const o=new Float32Array(i),l=i>65535?new Uint32Array(r):new Uint16Array(r),c=new Float32Array(n),u=new Float32Array(a),h=new Float32Array(a);let d=0,f=0,p=0,m=0,g=0;e.forEach(_=>{const y=Cs.GetLineLengthArray(_),v=y[y.length-1];for(let P=0,M=0;M<_.length;P++,M+=3){const R=d+M*2;if(o[R+0]=_[M+0],o[R+1]=_[M+1],o[R+2]=_[M+2],o[R+3]=_[M+0],o[R+4]=_[M+1],o[R+5]=_[M+2],M<_.length-3){const I=P*2+t,L=f+M*2;l[L+0]=I,l[L+1]=I+1,l[L+2]=I+2,l[L+3]=I+2,l[L+4]=I+1,l[L+5]=I+3}}t+=_.length/3*2;const x=_.length*2,A=o.subarray(d,d+x);d+=x,f+=(_.length-3)*2;const b=new Float32Array(A.length),C=new Float32Array(A.length),T=A.length/6;let w;bl._CompareV3(0,T-1,A)?w=A.subarray((T-2)*6,(T-1)*6):w=A.subarray(0,6),b.set(w),b.set(A.subarray(0,A.length-6),6),C.set(A.subarray(6)),bl._CompareV3(T-1,0,A)?w=A.subarray(6,12):w=A.subarray((T-1)*6,T*6),C.set(w,C.length-6);for(let P=0,M=A.length/3;P>1]/v;if(this._options.uvs)for(let P=0;PRa.Parse(s,e);class Ra extends l_e{constructor(e,t,i,r){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=r??[],i.points&&this.addPoints(Cs.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const p=Ra._ConvertToRibbonPath(d,c.ribbonOptions,this._scene.useRightHandedSystem,r&&r[f]);i=this._preprocess(p,i,c)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var u,h;const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const r=[],n=[],a=e[0];for(let d=0;d2)for(let d=0;d0&&(o[0]+=1,o[1]+=1),n.push(o[1]+(f%2!==0?i:0),o[0],o[2]),l&&n.push(o[0],o[1]+(f%2!==0?i:0),o[2])}else for(let d=0;dp.y&&p.x>p.z?i?Ra._RightHandedForwardReadOnlyQuaternion:Ra._LeftHandedForwardReadOnlyQuaternion:Ra._LeftReadOnlyQuaternion),c=p.normalize()}u=c.multiplyByFloats(o,o,o),n.push(d.add(u)),a.push(d.subtract(u))}r||(n.push(l[l.length-1].add(u)),a.push(l[l.length-1].subtract(u)))}return[n,a]}static _GetDirectionFromPoints(e,t,i){return e.x===t.x&&(!i||(i==null?void 0:i.x)===1)?Ra.DIRECTION_YZ:e.y===t.y?Ra.DIRECTION_XZ:e.z===t.z?Ra.DIRECTION_XY:Ra.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),r={},n=[];Nl.DeepCopy(this._pathsOptions,n,void 0,void 0,!0),Nl.DeepCopy(i,r,["instance"],void 0,!0);const a=new Ra(e,this._scene,r,n);return t&&(a.parent=t),a.material=this.material,a}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,r=e.name,n=e.pathOptions;return new Ra(r,t,i,n)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let a=0;a0){if(e.length%2!=0&&e.push(i),t===5){const o=Math.floor(e.length/2);for(let u=0,h=0;u0){if(t===5){const a=Math.floor(e.length/2);for(let o=0;o=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,s*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[s]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};Ee.prototype.thinInstanceSetAttributeAt=function(s,e,t,i=!0){return s===$.ColorKind&&(s=$.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[s]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(s,0),this._userThinInstanceBuffersStorage.data[s].set(t,e*this._userThinInstanceBuffersStorage.strides[s]),i&&this.thinInstanceBufferUpdated(s),!0)};Object.defineProperty(Ee.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(s){var i;const e=this._thinInstanceDataStorage.matrixData??((i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData),t=e?e.length/16:0;s<=t&&(this._thinInstanceDataStorage.instancesCount=s)},enumerable:!0,configurable:!0});Ee.prototype._thinInstanceCreateMatrixBuffer=function(s,e,t=!0){const i=new Mo(this.getEngine(),e,!t,16,!1,!0);for(let r=0;r<4;r++)this.setVerticesBuffer(i.createVertexBuffer(s+r,r*4,4));return i};Ee.prototype.thinInstanceSetBuffer=function(s,e,t=0,i=!0){var r,n,a;t=t||16,s==="matrix"?((r=this._thinInstanceDataStorage.matrixBuffer)==null||r.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=e?e.length:32*t,this._thinInstanceDataStorage.matrixData=e,this._thinInstanceDataStorage.worldMatrices=null,e!==null?(this._thinInstanceDataStorage.instancesCount=e.length/t,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",e,i),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):s==="previousMatrix"?((n=this._thinInstanceDataStorage.previousMatrixBuffer)==null||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(s===$.ColorKind&&(s=$.ColorInstanceKind),e===null?(a=this._userThinInstanceBuffersStorage)!=null&&a.data[s]&&(this.removeVerticesData(s),delete this._userThinInstanceBuffersStorage.data[s],delete this._userThinInstanceBuffersStorage.strides[s],delete this._userThinInstanceBuffersStorage.sizes[s],delete this._userThinInstanceBuffersStorage.vertexBuffers[s]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[s]=e,this._userThinInstanceBuffersStorage.strides[s]=t,this._userThinInstanceBuffersStorage.sizes[s]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[s]=new $(this.getEngine(),e,s,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[s])))};Ee.prototype.thinInstanceBufferUpdated=function(s){var e,t,i;s==="matrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(s),(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):s==="previousMatrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(s),(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(s===$.ColorKind&&(s=$.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[s]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[s].isUpdatable()&&this._thinInstanceRecreateBuffer(s),this._userThinInstanceBuffersStorage.vertexBuffers[s].updateDirectly(this._userThinInstanceBuffersStorage.data[s],0)))};Ee.prototype.thinInstancePartialBufferUpdate=function(s,e,t){var i;s==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(s===$.ColorKind&&(s=$.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[s]&&this._userThinInstanceBuffersStorage.vertexBuffers[s].updateDirectly(e,t))};Ee.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const s=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;ee.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){var t;return this.isConnected?(t=this._connectedPoint)!=null&&t._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=me.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new Ae,this.onDisconnectionObservable=new Ae,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===0}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==me.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?0:1;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return 1;let r=i,n=t;return this.direction===0&&(r=t,n=i),r.isAnAncestorOf(n)?2:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this),this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class Ri{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){const r=i.ownerBlock.getDescendantOfPredicate(e);if(r)return r}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new Ae,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=hz.UniqueId}registerInput(e,t,i=!1,r,n,a){const o=new xde(e,this,0);return o.type=t,o.isOptional=i,o.defaultValue=r,o.value=r,o.valueMin=n,o.valueMax=a,this._inputs.push(o),this}registerOutput(e,t,i){return i=i??new xde(e,this,1),i.type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some(i=>i.hasEndpoints)&&!this.isDebug)return!1;this.outputs.forEach(i=>i._resetCounters())}this._buildId=e.buildId;for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.notConnectedNonOptionalInputs.push(i);continue}const r=i.connectedPoint.ownerBlock;r&&r!==this&&r.build(e)}this._customBuildStep(e),e.verbose&&fe.Log(`Building ${this.name} [${this.getClassName()}]`);const t=Or.Now;this._buildBlock(e),this._buildExecutionTime=Or.Now-t;for(const i of this._outputs)for(const r of i.endpoints){const n=r.ownerBlock;n&&n.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter(i=>i.name===e);return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter(i=>i.name===e);return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.visibleOnFrame=this.visibleOnFrame,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(r=>{const n=this.inputs.find(a=>a.name===r.name);if(n&&(r.displayName&&(n.displayName=r.displayName),r.isExposedOnFrame&&(n.isExposedOnFrame=r.isExposedOnFrame,n.exposedPortPosition=r.exposedPortPosition),r.value!==void 0&&r.value!==null))if(r.valueType==="number")n.value=r.value;else{const a=Xn(r.valueType);a&&(n.value=a.FromArray(r.value))}}),i&&i.forEach((r,n)=>{r.displayName&&(this.outputs[n].displayName=r.displayName),r.isExposedOnFrame&&(this.outputs[n].isExposedOnFrame=r.isExposedOnFrame,this.outputs[n].exposedPortPosition=r.exposedPortPosition)})}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame}; `}_dumpCodeForOutputConnections(e){let t="";if(e.indexOf(this)!==-1)return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,n=r.ownerBlock;t+=n._dumpCodeForOutputConnections(e),t+=`${n._codeVariableName}.${n._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); `}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,e.indexOf(this._codeVariableName)!==-1){let a=0;do a++,this._codeVariableName=i+a;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let r=` // ${this.getClassName()} `;this.comments&&(r+=`// ${this.comments} `);const n=this.getClassName();if(n==="GeometryInputBlock"){const o=this.type;r+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${o}); `}else r+=`var ${this._codeVariableName} = new BABYLON.${n}("${this.name}"); `;r+=this._dumpPropertiesCode();for(const a of this.inputs){if(!a.isConnected)continue;const l=a.connectedPoint.ownerBlock;t.indexOf(l)===-1&&(r+=l._dumpCode(e,t))}for(const a of this.outputs)if(a.hasEndpoints)for(const o of a.endpoints){const l=o.ownerBlock;l&&t.indexOf(l)===-1&&(r+=l._dumpCode(e,t))}return r}clone(){const e=this.serialize(),t=Xn(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}F([X("comment")],Ri.prototype,"comments",void 0);class c_e extends Ri{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",me.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}ve("BABYLON.GeometryOutputBlock",c_e);var os;(function(s){s[s.None=0]="None",s[s.Positions=1]="Positions",s[s.Normals=2]="Normals",s[s.Tangents=3]="Tangents",s[s.UV=4]="UV",s[s.UV2=5]="UV2",s[s.UV3=6]="UV3",s[s.UV4=7]="UV4",s[s.UV5=8]="UV5",s[s.UV6=9]="UV6",s[s.Colors=10]="Colors",s[s.VertexID=11]="VertexID",s[s.FaceID=12]="FaceID",s[s.GeometryID=13]="GeometryID",s[s.CollectionID=14]="CollectionID",s[s.LoopID=15]="LoopID",s[s.InstanceID=16]="InstanceID"})(os||(os={}));class Sje{constructor(){this._rotationMatrix=new he,this._scalingMatrix=new he,this._positionMatrix=new he,this._scalingRotationMatrix=new he,this._transformMatrix=new he,this._tempVector3=new D,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case os.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?D.Zero():D.FromArray(this.geometryContext.positions,i*3);case os.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?D.Zero():D.FromArray(this.geometryContext.normals,i*3);case os.Colors:return!this.geometryContext||!this.geometryContext.colors?mt.Zero():mt.FromArray(this.geometryContext.colors,i*4);case os.Tangents:return!this.geometryContext||!this.geometryContext.tangents?mt.Zero():mt.FromArray(this.geometryContext.tangents,i*4);case os.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?we.Zero():we.FromArray(this.geometryContext.uvs,i*2);case os.UV2:return!this.geometryContext||!this.geometryContext.uvs2?we.Zero():we.FromArray(this.geometryContext.uvs2,i*2);case os.UV3:return!this.geometryContext||!this.geometryContext.uvs3?we.Zero():we.FromArray(this.geometryContext.uvs3,i*2);case os.UV4:return!this.geometryContext||!this.geometryContext.uvs4?we.Zero():we.FromArray(this.geometryContext.uvs4,i*2);case os.UV5:return!this.geometryContext||!this.geometryContext.uvs5?we.Zero():we.FromArray(this.geometryContext.uvs5,i*2);case os.UV6:return!this.geometryContext||!this.geometryContext.uvs6?we.Zero():we.FromArray(this.geometryContext.uvs6,i*2);case os.VertexID:return i;case os.FaceID:return this.executionContext.getExecutionFaceIndex();case os.LoopID:return this.executionContext.getExecutionLoopIndex();case os.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case os.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case os.CollectionID:return!this.geometryContext||!this.geometryContext.metadata?0:this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case me.Vector2:return new we(i,i);case me.Vector3:return new D(i,i,i);case me.Vector4:return new mt(i,i,i,i)}return null}adaptInput(e,t,i){var n;if(!e.isConnected)return e.value||i;const r=e.getConnectedValue(this);if(((n=e._connectedPoint)==null?void 0:n.type)===t)return r;switch(t){case me.Vector2:return new we(r,r);case me.Vector3:return new D(r,r,r);case me.Vector4:return new mt(r,r,r,r)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. `;for(const t of this.noContextualData)e+=`Contextual input ${os[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). `;if(e)throw`Build of NodeGeometry failed: `+e}_instantiate(e,t,i,r,n){he.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),he.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),he.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let a=0;at.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${os[this._contextualSource]}; `;const t=[];let i="";switch(this.type){case me.Float:case me.Int:i=`${this.value}`;break;case me.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case me.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case me.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break}return t.push(`${e}.value = ${i}`),(this.type===me.Float||this.type===me.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(`; `)}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,this._storedValue!==null&&!this.isContextual&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const t=Xn(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}ve("BABYLON.GeometryInputBlock",lo);class Iee extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",me.Float,!0,1),this.registerInput("width",me.Float,!0,0),this.registerInput("height",me.Float,!0,0),this.registerInput("depth",me.Float,!0,0),this.registerInput("subdivisions",me.Int,!0,1),this.registerInput("subdivisionsX",me.Int,!0,0),this.registerInput("subdivisionsY",me.Int,!0,0),this.registerInput("subdivisionsZ",me.Int,!0,0),this.registerOutput("geometry",me.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new lo("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new lo("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new lo("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new lo("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=r=>{t.size=this.size.getConnectedValue(r),t.width=this.width.getConnectedValue(r),t.height=this.height.getConnectedValue(r),t.depth=this.depth.getConnectedValue(r);const n=this.subdivisions.getConnectedValue(r),a=this.subdivisionsX.getConnectedValue(r),o=this.subdivisionsY.getConnectedValue(r),l=this.subdivisionsZ.getConnectedValue(r);return n&&(t.segments=n),a&&(t.widthSegments=a),o&&(t.heightSegments=o),l&&(t.depthSegments=l),vke(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Iee.prototype,"evaluateContext",void 0);ve("BABYLON.BoxBlock",Iee);class Qh{_getGlobalNodeGeometryEditor(){if(typeof NODEGEOMETRYEDITOR<"u")return NODEGEOMETRYEDITOR;if(typeof BABYLON<"u"&&typeof BABYLON.NodeGeometryEditor<"u")return BABYLON}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=Qh._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new Ae,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}get vertexData(){return this._vertexData}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return Me.Warn("More than one block was found with the name `"+e+"`"),t;return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),typeof this.BJSNODEGEOMETRYEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:Qh.EditorURL;Me.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e==null?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(e==null?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const r=Or.Now;this._initializeBlock(this.outputBlock,i);const n=new Sje;n.buildId=this._buildId,n.verbose=e,this.outputBlock.build(n),t&&(this._buildId=Qh._BuildIdGenerator++),this._buildExecutionTime=Or.Now-r,n.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=n.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Ee(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),this._vertexData?(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e):!1}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1&&this.attachedBlocks.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const n=r.ownerBlock;n!==e&&this._initializeBlock(n,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const r of e.blocks){const n=Xn(r.customType);if(n){const a=new n;a._deserialize(r),i[r.id]=a,this.attachedBlocks.push(a)}}for(const r of this.attachedBlocks)if(r.isTeleportOut){const n=r,a=n._tempEntryPointUniqueId;if(a){const o=i[a];o&&o.attachToEndpoint(n)}}for(let r=0;ro.targetConnectionName)&&!t||this._restoreConnections(a,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const a of r)i[a.blockId]&&(a.blockId=i[a.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const n=[];for(const a in i)n[a]=i[a].uniqueId;this.editorData.map=n}this.comment=e.comment}_restoreConnections(e,t,i){for(const r of e.outputs)for(const n of t.blocks){const a=i[n.id];if(a){for(const o of n.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===r.name){const l=a.getInputByName(o.inputName);if(!l||l.isConnected)continue;r.connectTo(l,!0),this._restoreConnections(a,t,i);continue}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); `;for(const n of t)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));return this.outputBlock&&(e=[],r+=`// Connections `,r+=this.outputBlock._dumpCodeForOutputConnections(e),r+=`// Output nodes `,r+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; `,r+=`nodeGeometry.build(); `),r}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const n=r.ownerBlock;n!==e&&this._gatherBlocks(n,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Iee("Box");e.autoConfigure();const t=new c_e("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=qe.Clone(()=>new Qh(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:qe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const r of i)t.blocks.push(r.serialize());if(!e)for(const r of this.attachedBlocks)i.indexOf(r)===-1&&t.blocks.push(r.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new Qh(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=qe.Parse(()=>new Qh(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(Qh.CreateDefault("blank")):new Promise((r,n)=>{const a=new On;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.nodeGeometry);t||(t=qe.Parse(()=>new Qh(e),l,null)),t.parseSerializedObject(l),t.snippetId=e;try{i||t.build(),r(t)}catch(c){n(c)}}else n("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}Qh._BuildIdGenerator=0;Qh.EditorURL=`${Me._DefaultCdnUrl}/v${Ge.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;Qh.SnippetUrl="https://snippet.babylonjs.com";F([X()],Qh.prototype,"name",void 0);F([X("comment")],Qh.prototype,"comment",void 0);class Pee extends Ri{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=ci,this.registerInput("geometry",me.Geometry),this.registerOutput("output",me.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(!this.geometry.isConnected)return null;const r=this.geometry.getConnectedValue(i),n=[],a={};for(let l=0;la[l]),o};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon}; `,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Pee.prototype,"evaluateContext",void 0);F([Jt("Epsilon",1,"ADVANCED",{notifiers:{rebuild:!0}})],Pee.prototype,"epsilon",void 0);ve("BABYLON.GeometryOptimizeBlock",Pee);class u_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",me.Float,!0,1),this.registerInput("width",me.Float,!0,0),this.registerInput("height",me.Float,!0,0),this.registerOutput("geometry",me.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new lo("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new lo("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new lo("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=r=>(t.size=this.size.getConnectedValue(r),t.width=this.width.getConnectedValue(r),t.height=this.height.getConnectedValue(r),vz(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],u_e.prototype,"evaluateContext",void 0);ve("BABYLON.PlaneBlock",u_e);class h_e extends Ri{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",me.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}const e=at.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=at.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=at.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}F([Jt("Serialize cached data",0,"ADVANCED",{notifiers:{rebuild:!0}})],h_e.prototype,"serializedCachedData",void 0);ve("BABYLON.MeshBlock",h_e);class d_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",me.Float,!0,1),this.registerInput("radiusX",me.Float,!0,0),this.registerInput("radiusY",me.Float,!0,0),this.registerInput("radiusZ",me.Float,!0,0),this.registerInput("subdivisions",me.Int,!0,4),this.registerOutput("geometry",me.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new lo("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=r=>(t.radius=this.radius.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),t.radiusX=this.radiusX.getConnectedValue(r),t.radiusY=this.radiusY.getConnectedValue(r),t.radiusZ=this.radiusZ.getConnectedValue(r),see(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],d_e.prototype,"evaluateContext",void 0);ve("BABYLON.IcoSphereBlock",d_e);class f_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",me.Int,!0,32),this.registerInput("diameter",me.Float,!0,1),this.registerInput("diameterX",me.Float,!0,0),this.registerInput("diameterY",me.Float,!0,0),this.registerInput("diameterZ",me.Float,!0,0),this.registerInput("arc",me.Float,!0,1),this.registerInput("slice",me.Float,!0,1),this.registerOutput("geometry",me.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new lo("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=r=>(t.segments=this.segments.getConnectedValue(r),t.diameter=this.diameter.getConnectedValue(r),t.diameterX=this.diameterX.getConnectedValue(r),t.diameterY=this.diameterY.getConnectedValue(r),t.diameterZ=this.diameterZ.getConnectedValue(r),t.arc=this.arc.getConnectedValue(r),t.slice=this.slice.getConnectedValue(r),ZJ(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],f_e.prototype,"evaluateContext",void 0);ve("BABYLON.SphereBlock",f_e);class p_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",me.Float,!0,1),this.registerInput("height",me.Float,!0,1),this.registerInput("subdivisions",me.Int,!0,1),this.registerInput("subdivisionsX",me.Int,!0,0),this.registerInput("subdivisionsY",me.Int,!0,0),this.registerOutput("geometry",me.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new lo("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new lo("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=r=>(t.width=this.width.getConnectedValue(r),t.height=this.height.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),t.subdivisionsX=this.subdivisionsX.getConnectedValue(r),t.subdivisionsY=this.subdivisionsY.getConnectedValue(r),P1(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],p_e.prototype,"evaluateContext",void 0);ve("BABYLON.GridBlock",p_e);class m_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",me.Float,!0,1),this.registerInput("thickness",me.Float,!0,.5),this.registerInput("tessellation",me.Int,!0,16),this.registerOutput("geometry",me.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new lo("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=r=>(t.thickness=this.thickness.getConnectedValue(r),t.diameter=this.diameter.getConnectedValue(r),t.tessellation=this.tessellation.getConnectedValue(r),XJ(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],m_e.prototype,"evaluateContext",void 0);ve("BABYLON.TorusBlock",m_e);class g_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",me.Float,!0,25),this.registerInput("diameter",me.Float,!0,1),this.registerInput("diameterTop",me.Float,!0,-1),this.registerInput("diameterBottom",me.Float,!0,-1),this.registerInput("subdivisions",me.Int,!0,1),this.registerInput("tessellation",me.Int,!0,24),this.registerInput("arc",me.Float,!0,1),this.registerOutput("geometry",me.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new lo("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new lo("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=r=>(t.height=this.height.getConnectedValue(r),t.diameter=this.diameter.getConnectedValue(r),t.diameterTop=this.diameterTop.getConnectedValue(r),t.diameterBottom=this.diameterBottom.getConnectedValue(r),t.diameterTop===-1&&(t.diameterTop=t.diameter),t.diameterBottom===-1&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),t.arc=this.arc.getConnectedValue(r),QJ(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],g_e.prototype,"evaluateContext",void 0);ve("BABYLON.CylinderBlock",g_e);class __e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",me.Float,!0,1),this.registerInput("radius",me.Float,!0,.25),this.registerInput("tessellation",me.Int,!0,16),this.registerInput("subdivisions",me.Int,!0,2),this.registerOutput("geometry",me.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new lo("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new lo("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=r=>(t.height=this.height.getConnectedValue(r),t.radius=this.radius.getConnectedValue(r),t.tessellation=this.tessellation.getConnectedValue(r),t.subdivisions=this.subdivisions.getConnectedValue(r),qJ(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],__e.prototype,"evaluateContext",void 0);ve("BABYLON.CapsuleBlock",__e);class v_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",me.Float,!0,.5),this.registerInput("tessellation",me.Int,!0,64),this.registerInput("arc",me.Float,!0,1),this.registerOutput("geometry",me.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new lo("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=r=>(t.radius=this.radius.getConnectedValue(r),t.tessellation=this.tessellation.getConnectedValue(r),t.arc=this.arc.getConnectedValue(r),JJ(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const r=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,r.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],v_e.prototype,"evaluateContext",void 0);ve("BABYLON.DiscBlock",v_e);class Eje extends Ri{constructor(e){super(e),this.registerOutput("geometry",me.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}ve("BABYLON.NullBlock",Eje);class y_e extends Ri{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",me.Geometry),this.registerInput("positions",me.Vector3),this.registerOutput("output",me.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}const r=[],n=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{var n;if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);const r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes()),this.left.onDisconnectionObservable.add(()=>this._updateInputOutputTypes()),this.right.onConnectionObservable.add(()=>this._updateInputOutputTypes()),this.right.onDisconnectionObservable.add(()=>this._updateInputOutputTypes())]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const r=t.type===me.Float||t.type===me.Int,n=i.type===me.Float||i.type===me.Int,a=r&&n;switch(this.operation){case Pu.Add:{a?e=o=>t.getConnectedValue(o)+i.getConnectedValue(o):r?e=o=>o.adapt(t,i.type).add(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).add(o.adapt(i,t.type));break}case Pu.Subtract:{a?e=o=>t.getConnectedValue(o)-i.getConnectedValue(o):r?e=o=>o.adapt(t,i.type).subtract(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).subtract(o.adapt(i,t.type));break}case Pu.Multiply:{a?e=o=>t.getConnectedValue(o)*i.getConnectedValue(o):r?e=o=>o.adapt(t,i.type).multiply(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).multiply(o.adapt(i,t.type));break}case Pu.Divide:{a?e=o=>t.getConnectedValue(o)/i.getConnectedValue(o):r?e=o=>o.adapt(t,i.type).divide(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).divide(o.adapt(i,t.type));break}case Pu.Min:{if(a)e=o=>Math.min(t.getConnectedValue(o),i.getConnectedValue(o));else{const[o,l]=r?[i,t]:[t,i];switch(o.type){case me.Vector2:{e=c=>we.Minimize(o.getConnectedValue(c),c.adapt(l,o.type));break}case me.Vector3:{e=c=>D.Minimize(o.getConnectedValue(c),c.adapt(l,o.type));break}case me.Vector4:{e=c=>mt.Minimize(o.getConnectedValue(c),c.adapt(l,o.type));break}}}break}case Pu.Max:if(a)e=o=>Math.max(t.getConnectedValue(o),i.getConnectedValue(o));else{const[o,l]=r?[i,t]:[t,i];switch(o.type){case me.Vector2:{e=c=>we.Maximize(o.getConnectedValue(c),c.adapt(l,o.type));break}case me.Vector3:{e=c=>D.Maximize(o.getConnectedValue(c),c.adapt(l,o.type));break}case me.Vector4:{e=c=>mt.Maximize(o.getConnectedValue(c),c.adapt(l,o.type));break}}break}}this.output._storedFunction=o=>t.type===me.Int?e(o)|0:e(o)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${Pu[this.operation]}; `}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===me.Int||this.left.type===me.Float&&this.right.type!==me.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[me.Int,me.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),(t.type===me.Int||t.type===me.Float)&&e.acceptedConnectionPointTypes.push(me.Vector2,me.Vector3,me.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach(e=>e.remove()),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}F([Jt("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:Pu.Add},{label:"Subtract",value:Pu.Subtract},{label:"Multiply",value:Pu.Multiply},{label:"Divide",value:Pu.Divide},{label:"Max",value:Pu.Max},{label:"Min",value:Pu.Min}]})],C_e.prototype,"operation",void 0);ve("BABYLON.MathBlock",C_e);class Tje extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerInput("fromMin",me.Float,!0,0),this.registerInput("fromMax",me.Float,!0,1),this.registerInput("toMin",me.Float,!0,0),this.registerInput("toMax",me.Float,!0,1),this.registerOutput("output",me.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(me.Vector2),this._inputs[0].excludedConnectionPointTypes.push(me.Vector3),this._inputs[0].excludedConnectionPointTypes.push(me.Vector4),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),n=this.toMin.getConnectedValue(e),a=this.toMax.getConnectedValue(e),o=(t-i)/(r-i)*(a-n)+n;return this.output.type===me.Int?Math.floor(o):o}}}ve("BABYLON.MapRangeBlock",Tje);var nl;(function(s){s[s.Equal=0]="Equal",s[s.NotEqual=1]="NotEqual",s[s.LessThan=2]="LessThan",s[s.GreaterThan=3]="GreaterThan",s[s.LessOrEqual=4]="LessOrEqual",s[s.GreaterOrEqual=5]="GreaterOrEqual",s[s.Xor=6]="Xor",s[s.Or=7]="Or",s[s.And=8]="And"})(nl||(nl={}));class S_e extends Ri{constructor(e){super(e),this.test=nl.Equal,this.registerInput("left",me.Float),this.registerInput("right",me.Float,!0,0),this.registerInput("ifTrue",me.AutoDetect,!0,1),this.registerInput("ifFalse",me.AutoDetect,!0,0),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=me.Float,this._inputs[0].acceptedConnectionPointTypes.push(me.Int),this._inputs[1].acceptedConnectionPointTypes.push(me.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t);let n=!1;switch(this.test){case nl.Equal:n=At.WithinEpsilon(i,r,ci);break;case nl.NotEqual:n=i!==r;break;case nl.LessThan:n=ir;break;case nl.LessOrEqual:n=i<=r;break;case nl.GreaterOrEqual:n=i>=r;break;case nl.Xor:n=!!i&&!r||!i&&!!r;break;case nl.Or:n=!!i||!!r;break;case nl.And:n=!!i&&!!r;break}return n};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${nl[this.test]}; `}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}F([Jt("Test",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:nl.Equal},{label:"NotEqual",value:nl.NotEqual},{label:"LessThan",value:nl.LessThan},{label:"GreaterThan",value:nl.GreaterThan},{label:"LessOrEqual",value:nl.LessOrEqual},{label:"GreaterOrEqual",value:nl.GreaterOrEqual},{label:"Xor",value:nl.Xor},{label:"Or",value:nl.Or},{label:"And",value:nl.And}]})],S_e.prototype,"test",void 0);ve("BABYLON.ConditionBlock",S_e);var Nd;(function(s){s[s.None=0]="None",s[s.LoopID=1]="LoopID",s[s.InstanceID=2]="InstanceID",s[s.Once=3]="Once"})(Nd||(Nd={}));class E_e extends Ri{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Nd.None,this.registerInput("min",me.AutoDetect),this.registerInput("max",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture),this._inputs[1].excludedConnectionPointTypes.push(me.Matrix),this._inputs[1].excludedConnectionPointTypes.push(me.Geometry),this._inputs[1].excludedConnectionPointTypes.push(me.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new lo("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new lo("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case me.Int:case me.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,r=this.max.getConnectedValue(t)||0;return i+Math.random()*(r-i)};break}case me.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||we.Zero(),r=this.max.getConnectedValue(t)||we.Zero();return new we(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y))};break}case me.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||D.Zero(),r=this.max.getConnectedValue(t)||D.Zero();return new D(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y),i.z+Math.random()*(r.z-i.z))};break}case me.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||mt.Zero(),r=this.max.getConnectedValue(t)||mt.Zero();return new mt(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y),i.z+Math.random()*(r.z-i.z),i.w+Math.random()*(r.w-i.w))};break}}this.lockMode===Nd.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Nd.InstanceID:i=t.getContextualValue(os.InstanceID,!0)||0;break;case Nd.LoopID:i=t.getContextualValue(os.LoopID,!0)||0;break;case Nd.Once:i=t.buildId||0;break}return(this._currentLockId!==i||this.lockMode===Nd.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Nd[this.lockMode]}; `}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}F([Jt("LockMode",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Nd.None},{label:"LoopID",value:Nd.LoopID},{label:"InstanceID",value:Nd.InstanceID},{label:"Once",value:Nd.Once}]})],E_e.prototype,"lockMode",void 0);ve("BABYLON.RandomBlock",E_e);class Mje extends Ri{constructor(e){super(e),this.registerInput("offset",me.Vector3,!0,D.Zero()),this.registerInput("scale",me.Float,!0,1),this.registerInput("octaves",me.Float,!0,2,0,16),this.registerInput("roughness",me.Float,!0,.5,0,1),this.registerOutput("output",me.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return t!==0?-e:e}_noiseGrad(e,t,i,r){const n=e&15,a=n<8?t:i,o=n===12||n==14?t:r,l=n<4?i:o;return this._negateIf(a,n&a)+this._negateIf(l,n&2)}_fade(e){return e*e*e*(e*(e*6-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,n,a;return r=n=a=3735928584,a+=i,n+=t,r+=e,a^=n,a-=this._hashBitRotate(n,14),r^=a,r-=this._hashBitRotate(a,11),n^=r,n-=this._hashBitRotate(r,25),a^=n,a-=this._hashBitRotate(n,16),r^=a,r-=this._hashBitRotate(a,4),n^=r,n-=this._hashBitRotate(r,14),a^=n,a-=this._hashBitRotate(n,24),a}_mix(e,t,i,r,n,a,o,l,c,u,h){const d=1-c,f=1-u;return(1-h)*(f*(e*d+t*c)+u*(i*d+r*c))+h*(f*(n*d+a*c)+u*(o*d+l*c))}_perlinNoise(e){const t=(e.x|0)-(e.x<0?1:0),i=(e.y|0)-(e.y<0?1:0),r=(e.z|0)-(e.z<0?1:0),n=e.x-t,a=e.y-i,o=e.z-r,l=this._fade(n),c=this._fade(a),u=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,r),n,a,o),this._noiseGrad(this._hash(t+1,i,r),n-1,a,o),this._noiseGrad(this._hash(t,i+1,r),n,a-1,o),this._noiseGrad(this._hash(t+1,i+1,r),n-1,a-1,o),this._noiseGrad(this._hash(t,i,r+1),n,a,o-1),this._noiseGrad(this._hash(t+1,i,r+1),n-1,a,o-1),this._noiseGrad(this._hash(t,i+1,r+1),n,a-1,o-1),this._noiseGrad(this._hash(t+1,i+1,r+1),n-1,a-1,o-1),l,c,u)}_perlinSigned(e){return this._perlinNoise(e)*.982}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,n){const a=new D(i.x*n+r.x,i.y*n+r.y,i.z*n+r.z);let o=1,l=1,c=0,u=0;e=At.Clamp(e,0,15);const h=e|0;for(let m=0;m<=h;m++){const g=this._perlin(a.scale(o));u+=g*l,c+=l,l*=At.Clamp(t,0,1),o*=2}const d=e-Math.floor(e);if(d==0)return u/c;const f=this._perlin(a.scale(o));let p=u+f*l;return u/=c,p/=c+l,(1-d)*u+d*p}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(os.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),n=this.offset.getConnectedValue(e),a=this.scale.getConnectedValue(e);return this.noise(i,r,t,n,a)}}}ve("BABYLON.NoiseBlock",Mje);class T_e extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",me.Geometry),this.registerInput("geometry1",me.Geometry,!0),this.registerInput("geometry2",me.Geometry,!0),this.registerInput("geometry3",me.Geometry,!0),this.registerInput("geometry4",me.Geometry,!0),this.registerOutput("output",me.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{const r=[];if(this.geometry0.isConnected){const o=this.geometry0.getConnectedValue(i);o&&r.push(o)}if(this.geometry1.isConnected){const o=this.geometry1.getConnectedValue(i);o&&r.push(o)}if(this.geometry2.isConnected){const o=this.geometry2.getConnectedValue(i);o&&r.push(o)}if(this.geometry3.isConnected){const o=this.geometry3.getConnectedValue(i);o&&r.push(o)}if(this.geometry4.isConnected){const o=this.geometry4.getConnectedValue(i);o&&r.push(o)}if(r.length===0)return null;let n=r[0].clone();const a=r.slice(1);return a.length&&n&&(n=n.merge(a,!0,!1,!0,!0)),n};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],T_e.prototype,"evaluateContext",void 0);ve("BABYLON.MergeGeometryBlock",T_e);class M_e extends Ri{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",me.Geometry,!0),this.registerInput("geometry1",me.Geometry,!0),this.registerInput("geometry2",me.Geometry,!0),this.registerInput("geometry3",me.Geometry,!0),this.registerInput("geometry4",me.Geometry,!0),this.registerInput("geometry5",me.Geometry,!0),this.registerInput("geometry6",me.Geometry,!0),this.registerInput("geometry7",me.Geometry,!0),this.registerInput("geometry8",me.Geometry,!0),this.registerInput("geometry9",me.Geometry,!0),this.registerOutput("output",me.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){const n=e.getConnectedValue(t);if(!n)return;n.metadata=n.metadata||{},n.metadata.collectionId=i,r.push(n)}}_buildBlock(e){const t=i=>{const r=[];return this._storeGeometry(this.geometry0,i,0,r),this._storeGeometry(this.geometry1,i,1,r),this._storeGeometry(this.geometry2,i,2,r),this._storeGeometry(this.geometry3,i,3,r),this._storeGeometry(this.geometry4,i,4,r),this._storeGeometry(this.geometry5,i,5,r),this._storeGeometry(this.geometry6,i,6,r),this._storeGeometry(this.geometry7,i,7,r),this._storeGeometry(this.geometry8,i,8,r),this._storeGeometry(this.geometry9,i,9,r),r.length?r[Math.round(Math.random()*(r.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],M_e.prototype,"evaluateContext",void 0);ve("BABYLON.GeometryCollectionBlock",M_e);class Rje extends Ri{constructor(e){super(e),this.registerInput("input",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=r=>i.getConnectedValue(r)}}ve("BABYLON.GeometryElbowBlock",Rje);class Ije extends Ri{constructor(e){super(e),this.registerInput("geometry",me.Geometry),this.registerOutput("output",me.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),at.ComputeNormals(t.positions,t.indices,t.normals),t}}}ve("BABYLON.ComputeNormalsBlock",Ije);class Pje extends Ri{constructor(e){super(e),this.registerInput("xyzw ",me.Vector4,!0),this.registerInput("xyz ",me.Vector3,!0),this.registerInput("xy ",me.Vector2,!0),this.registerInput("zw ",me.Vector2,!0),this.registerInput("x ",me.Float,!0),this.registerInput("y ",me.Float,!0),this.registerInput("z ",me.Float,!0),this.registerInput("w ",me.Float,!0),this.registerOutput("xyzw",me.Vector4),this.registerOutput("xyz",me.Vector3),this.registerOutput("xy",me.Vector2),this.registerOutput("zw",me.Vector2),this.registerOutput("x",me.Float),this.registerOutput("y",me.Float),this.registerOutput("z",me.Float),this.registerOutput("w",me.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e==="x "?"xIn":e==="y "?"yIn":e==="z "?"zIn":e==="w "?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,r=this.zIn,n=this.wIn,a=this.xyIn,o=this.zwIn,l=this.xyzIn,c=this.xyzwIn,u=this.xyzwOut,h=this.xyzOut,d=this.xyOut,f=this.zwOut,p=this.xOut,m=this.yOut,g=this.zOut,_=this.wOut,y=v=>{if(c.isConnected)return c.getConnectedValue(v);let x=0,A=0,b=0,C=0;if(t.isConnected&&(x=t.getConnectedValue(v)),i.isConnected&&(A=i.getConnectedValue(v)),r.isConnected&&(b=r.getConnectedValue(v)),n.isConnected&&(C=n.getConnectedValue(v)),a.isConnected){const T=a.getConnectedValue(v);T&&(x=T.x,A=T.y)}if(o.isConnected){const T=o.getConnectedValue(v);T&&(b=T.x,C=T.y)}if(l.isConnected){const T=l.getConnectedValue(v);T&&(x=T.x,A=T.y,b=T.z)}return new mt(x,A,b,C)};u._storedFunction=v=>y(v),h._storedFunction=v=>{const x=y(v);return new D(x.x,x.y,x.z)},d._storedFunction=v=>{const x=y(v);return new we(x.x,x.y)},f._storedFunction=v=>{const x=y(v);return new we(x.z,x.w)},p._storedFunction=v=>y(v).x,m._storedFunction=v=>y(v).y,g._storedFunction=v=>y(v).z,_._storedFunction=v=>y(v).w}}ve("BABYLON.VectorConverterBlock",Pje);class wje extends Ri{constructor(e){super(e),this.registerInput("input",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=t=>this.input.getConnectedValue(t).normalize()}}ve("BABYLON.NormalizeVectorBlock",wje);class R_e extends Ri{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",me.Geometry),this.registerInput("id",me.Int,!0,0),this.registerOutput("output",me.Geometry),this.id.acceptedConnectionPointTypes.push(me.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const t=i=>{const r=this.geometry.getConnectedValue(i);if(!r||!r.indices||!r.positions)return r;const n=new GB;return n.materialIndex=this.id.getConnectedValue(i)|0,n.indexStart=0,n.indexCount=r.indices.length,n.verticesStart=0,n.verticesCount=r.positions.length/3,r.materialInfos=[n],r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],R_e.prototype,"evaluateContext",void 0);ve("BABYLON.SetMaterialIDBlock",R_e);var Xr;(function(s){s[s.Cos=0]="Cos",s[s.Sin=1]="Sin",s[s.Abs=2]="Abs",s[s.Exp=3]="Exp",s[s.Round=4]="Round",s[s.Floor=5]="Floor",s[s.Ceiling=6]="Ceiling",s[s.Sqrt=7]="Sqrt",s[s.Log=8]="Log",s[s.Tan=9]="Tan",s[s.ArcTan=10]="ArcTan",s[s.ArcCos=11]="ArcCos",s[s.ArcSin=12]="ArcSin",s[s.Sign=13]="Sign",s[s.Negate=14]="Negate",s[s.OneMinus=15]="OneMinus",s[s.Reciprocal=16]="Reciprocal",s[s.ToDegrees=17]="ToDegrees",s[s.ToRadians=18]="ToRadians",s[s.Fract=19]="Fract",s[s.Exp2=20]="Exp2"})(Xr||(Xr={}));class I_e extends Ri{constructor(e){super(e),this.operation=Xr.Cos,this.registerInput("input",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case Xr.Cos:{t=i=>Math.cos(i);break}case Xr.Sin:{t=i=>Math.sin(i);break}case Xr.Abs:{t=i=>Math.abs(i);break}case Xr.Exp:{t=i=>Math.exp(i);break}case Xr.Exp2:{t=i=>Math.pow(2,i);break}case Xr.Round:{t=i=>Math.round(i);break}case Xr.Floor:{t=i=>Math.floor(i);break}case Xr.Ceiling:{t=i=>Math.ceil(i);break}case Xr.Sqrt:{t=i=>Math.sqrt(i);break}case Xr.Log:{t=i=>Math.log(i);break}case Xr.Tan:{t=i=>Math.tan(i);break}case Xr.ArcTan:{t=i=>Math.atan(i);break}case Xr.ArcCos:{t=i=>Math.acos(i);break}case Xr.ArcSin:{t=i=>Math.asin(i);break}case Xr.Sign:{t=i=>Math.sign(i);break}case Xr.Negate:{t=i=>-i;break}case Xr.OneMinus:{t=i=>1-i;break}case Xr.Reciprocal:{t=i=>1/i;break}case Xr.ToRadians:{t=i=>i*Math.PI/180;break}case Xr.ToDegrees:{t=i=>i*180/Math.PI;break}case Xr.Fract:{t=i=>i>=0?i-Math.floor(i):i-Math.ceil(i);break}}if(!t){this.output._storedFunction=null,this.output._storedValue=null;return}switch(this.input.type){case me.Int:case me.Float:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return t(r)};break}case me.Vector2:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return new we(t(r.x),t(r.y))};break}case me.Vector3:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return new D(t(r.x),t(r.y),t(r.z))};break}case me.Vector4:{this.output._storedFunction=i=>{const r=this.input.getConnectedValue(i);return new mt(t(r.x),t(r.y),t(r.z),t(r.w))};break}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${Xr[this.operation]}; `}}F([Jt("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Xr.Cos},{label:"Sin",value:Xr.Sin},{label:"Abs",value:Xr.Abs},{label:"Exp",value:Xr.Exp},{label:"Exp2",value:Xr.Exp2},{label:"Round",value:Xr.Round},{label:"Floor",value:Xr.Floor},{label:"Ceiling",value:Xr.Ceiling},{label:"Sqrt",value:Xr.Sqrt},{label:"Log",value:Xr.Log},{label:"Tan",value:Xr.Tan},{label:"ArcTan",value:Xr.ArcTan},{label:"ArcCos",value:Xr.ArcCos},{label:"ArcSin",value:Xr.ArcSin},{label:"Sign",value:Xr.Sign},{label:"Negate",value:Xr.Negate},{label:"OneMinus",value:Xr.OneMinus},{label:"Reciprocal",value:Xr.Reciprocal},{label:"ToDegrees",value:Xr.ToDegrees},{label:"ToRadians",value:Xr.ToRadians},{label:"Fract",value:Xr.Fract}]})],I_e.prototype,"operation",void 0);ve("BABYLON.GeometryTrigonometryBlock",I_e);class P_e extends Ri{constructor(e){super(e),this._rotationMatrix=new he,this._scalingMatrix=new he,this._translationMatrix=new he,this._scalingRotationMatrix=new he,this._transformMatrix=new he,this.evaluateContext=!0,this.registerInput("value",me.AutoDetect),this.registerInput("matrix",me.Matrix,!0),this.registerInput("translation",me.Vector3,!0,D.Zero()),this.registerInput("rotation",me.Vector3,!0,D.Zero()),this.registerInput("scaling",me.Vector3,!0,D.One()),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const t=i=>{const r=this.value.getConnectedValue(i);if(!r)return null;let n;if(this.matrix.isConnected)n=this.matrix.getConnectedValue(i);else{const a=this.scaling.getConnectedValue(i),o=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);he.ScalingToRef(a.x,a.y,a.z,this._scalingMatrix),he.RotationYawPitchRollToRef(o.y,o.x,o.z,this._rotationMatrix),he.TranslationToRef(l.x,l.y,l.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),n=this._transformMatrix}switch(this.value.type){case me.Geometry:{const a=r.clone();return a.transform(n),a}case me.Vector2:return we.Transform(r,n);case me.Vector3:return D.TransformCoordinates(r,n);case me.Vector4:return mt.TransformCoordinates(r,n)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],P_e.prototype,"evaluateContext",void 0);ve("BABYLON.GeometryTransformBlock",P_e);class Dje extends Ri{constructor(e){super(e),this.registerInput("angle",me.Float,!1,0),this.registerOutput("matrix",me.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new lo("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>he.RotationX(this.angle.getConnectedValue(t))}}ve("BABYLON.RotationXBlock",Dje);class Lje extends Ri{constructor(e){super(e),this.registerInput("angle",me.Float,!1,0),this.registerOutput("matrix",me.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new lo("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>he.RotationY(this.angle.getConnectedValue(t))}}ve("BABYLON.RotationYBlock",Lje);class Oje extends Ri{constructor(e){super(e),this.registerInput("angle",me.Float,!1,0),this.registerOutput("matrix",me.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new lo("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>he.RotationZ(this.angle.getConnectedValue(t))}}ve("BABYLON.RotationZBlock",Oje);class Nje extends Ri{constructor(e){super(e),this.registerInput("scale",me.Vector3,!1,D.One()),this.registerOutput("matrix",me.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new lo("Scale");e.value=new D(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return he.Scaling(i.x,i.y,i.z)}}}ve("BABYLON.ScalingBlock",Nje);class Fje extends Ri{constructor(e){super(e),this.registerInput("source",me.Vector3,!0,D.Up()),this.registerInput("target",me.Vector3,!0,D.Left()),this.registerOutput("matrix",me.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.source.getConnectedValue(t).clone(),r=this.target.getConnectedValue(t).clone(),n=new he;return i.normalize(),r.normalize(),he.RotationAlignToRef(i,r,n,!0),n}}}ve("BABYLON.AlignBlock",Fje);class Bje extends Ri{constructor(e){super(e),this.registerInput("translation",me.Vector3,!1,D.Zero()),this.registerOutput("matrix",me.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new lo("Translation");e.value=new D(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return he.Translation(i.x,i.y,i.z)}}}ve("BABYLON.TranslationBlock",Bje);class Dee extends Ri{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",me.Geometry),this.registerInput("instance",me.Geometry,!0),this.registerInput("density",me.Float,!0,1,0,1),this.registerInput("matrix",me.Matrix,!0),this.registerInput("rotation",me.Vector3,!0,D.Zero()),this.registerInput("scaling",me.Vector3,!0,D.One()),this.scaling.acceptedConnectionPointTypes.push(me.Float),this.registerOutput("output",me.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let r=this._vertexData.positions.length/3;const n=[],a=new D,o=[];let l=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexu)continue;a.fromArray(l,this._currentIndex*3);const h=c.clone();if(this.matrix.isConnected){const d=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(h,a,d,n)}else{const d=i.adaptInput(this.scaling,me.Vector3,D.OneReadOnly),f=this.rotation.getConnectedValue(i)||D.ZeroReadOnly;i._instantiate(h,a,f,d,n)}this._currentLoopIndex++}if(i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),n.length)if(n.length===1)this._vertexData=n[0];else{const c=n.splice(0,1)[0];this._vertexData=c.merge(n,!0,!1,!0,!0)}else return null;return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; `;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Dee.prototype,"evaluateContext",void 0);F([Jt("Remove duplicated positions",0,"ADVANCED",{notifiers:{update:!0}})],Dee.prototype,"removeDuplicatedPositions",void 0);ve("BABYLON.InstantiateOnVerticesBlock",Dee);class w_e extends Ri{constructor(e){super(e),this._currentPosition=new D,this._currentUV=new we,this._vertex0=new D,this._vertex1=new D,this._vertex2=new D,this._tempVector0=new D,this._tempVector1=new D,this._uv0=new we,this._uv1=new we,this._uv2=new we,this.evaluateContext=!0,this.registerInput("geometry",me.Geometry),this.registerInput("instance",me.Geometry,!0),this.registerInput("count",me.Int,!0,256),this.registerInput("matrix",me.Matrix,!0),this.registerInput("rotation",me.Vector3,!0,D.Zero()),this.registerInput("scaling",me.Vector3,!0,D.One()),this.scaling.acceptedConnectionPointTypes.push(me.Float),this.registerOutput("output",me.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),D.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let r=null;const n=this.count.getConnectedValue(i),a=this._vertexData.indices.length/3,o=n/a;let l=0;const c=[];let u=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=n);m++){let g=Math.random(),_=Math.random();if(g>_){const b=g;g=_,_=b}const y=g,v=_-g,x=1-y-v;if(this._currentPosition.set(y*this._vertex0.x+v*this._vertex1.x+x*this._vertex2.x,y*this._vertex0.y+v*this._vertex1.y+x*this._vertex2.y,y*this._vertex0.z+v*this._vertex1.z+x*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(y*this._uv0.x+v*this._uv1.x+x*this._uv2.x,y*this._uv0.y+v*this._uv1.y+x*this._uv2.y),r=this.instance.getConnectedValue(i),!r||!r.positions||r.positions.length===0){l-=o;continue}const A=r.clone();if(this.matrix.isConnected){const b=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(A,this._currentPosition,b,c)}else{const b=i.adaptInput(this.scaling,me.Vector3,D.OneReadOnly),C=this.rotation.getConnectedValue(i)||D.ZeroReadOnly;i._instantiate(A,this._currentPosition,C,b,c)}u++,this._currentLoopIndex++}}if(c.length)if(c.length===1)this._vertexData=c[0];else{const h=c.splice(0,1)[0];this._vertexData=h.merge(c,!0,!1,!0,!0)}return i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],w_e.prototype,"evaluateContext",void 0);ve("BABYLON.InstantiateOnFacesBlock",w_e);class Lee extends Ri{constructor(e){super(e),this._currentPosition=new D,this._vertex0=new D,this._vertex1=new D,this._vertex2=new D,this.evaluateContext=!0,this.gridMode=!1,this.registerInput("geometry",me.Geometry),this.registerInput("instance",me.Geometry,!0),this.registerInput("count",me.Int,!0,256),this.registerInput("matrix",me.Matrix,!0),this.registerInput("rotation",me.Vector3,!0,D.Zero()),this.registerInput("scaling",me.Vector3,!0,D.One()),this.registerInput("gridSize",me.Int,!0,10),this.scaling.acceptedConnectionPointTypes.push(me.Float),this.registerOutput("output",me.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get gridSize(){return this._inputs[6]}get output(){return this._outputs[0]}_getValueOnGrid(e,t,i,r){const n=(r-i)/t;return i+n/2+e*n}_getIndexinGrid(e,t,i,r){return e+t*r+i*r*r}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let r=null;const n=this.count.getConnectedValue(i),a=[],o=JS(this._vertexData.positions,0,this._vertexData.positions.length/3),l=o.minimum,c=o.maximum,u=new D(.5,.8,.2),h=this._vertexData.indices.length/3,d=this.gridSize.getConnectedValue(i);this._currentLoopIndex=0;let f;if(this.gridMode){f=[];for(let p=0;p0&&g++}if(g%2===0){p--;continue}if(r=this.instance.getConnectedValue(i),!r||!r.positions||r.positions.length===0)continue;const _=r.clone();if(this.matrix.isConnected){const y=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(_,this._currentPosition,y,a)}else{const y=i.adaptInput(this.scaling,me.Vector3,D.OneReadOnly),v=this.rotation.getConnectedValue(i)||D.ZeroReadOnly;i._instantiate(_,this._currentPosition,v,y,a)}this._currentLoopIndex++}if(a.length)if(a.length===1)this._vertexData=a[0];else{const p=a.splice(0,1)[0];this._vertexData=p.merge(a,!0,!1,!0,!0)}return i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `;return e+=`${this._codeVariableName}.gridMode = ${this.gridMode?"true":"false"}; `,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.gridMode=this.gridMode,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext),e.gridMode!==void 0&&(this.gridMode=e.gridMode)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Lee.prototype,"evaluateContext",void 0);F([Jt("Grid mode",0,"MODES",{notifiers:{rebuild:!0}})],Lee.prototype,"gridMode",void 0);ve("BABYLON.InstantiateOnVolumeBlock",Lee);class Oee extends Ri{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",me.Geometry,!0),this.registerInput("count",me.Int,!0,1),this.registerOutput("output",me.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Oee.prototype,"evaluateContext",void 0);class kje extends Oee{constructor(e){super(e),this.registerInput("matrix",me.Matrix,!0),this.registerInput("position",me.Vector3,!0,D.Zero()),this.registerInput("rotation",me.Vector3,!0,D.Zero()),this.registerInput("scaling",me.Vector3,!0,D.One()),this.scaling.acceptedConnectionPointTypes.push(me.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=i=>{i.pushExecutionContext(this),i.pushInstancingContext(this);const r=this.count.getConnectedValue(i),n=[];for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const r=this.count.getConnectedValue(i),n=[],a=he.Identity(),o=D.Zero(),l=D.Zero(),c=D.Zero();for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const r=this.count.getConnectedValue(i),n=[],a=he.Identity(),o=he.Identity(),l=he.Identity(),c=D.Zero(),u=D.Zero(),h=D.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}ve("BABYLON.IntFloatConverterBlock",Vje);class Gje extends Ri{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];const t=i=>{const r=this.input.getConnectedValue(i);if(r==null)return this.log.push(["null",""]),r;switch(this.input.type){case me.Vector2:this.log.push([pje(r,4),r.toString()]);break;case me.Vector3:this.log.push([mje(r,4),r.toString()]);break;case me.Vector4:this.log.push([gje(r,4),r.toString()]);break;default:this.log.push([r.toString(),r.toString()]);break}return r};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}ve("BABYLON.DebugBlock",Gje);class Wje extends Ri{constructor(e){super(e),this.registerInput("geometry",me.Geometry),this.registerOutput("output",me.Geometry),this.registerOutput("id",me.Int),this.registerOutput("collectionId",me.Int),this.registerOutput("verticesCount",me.Int),this.registerOutput("facesCount",me.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}ve("BABYLON.GeometryInfoBlock",Wje);var Vm;(function(s){s[s.Spherical=0]="Spherical",s[s.Cylindrical=1]="Cylindrical",s[s.Cubic=2]="Cubic"})(Vm||(Vm={}));class D_e extends Ri{constructor(e){super(e),this.mapping=Vm.Spherical,this.registerInput("position",me.Vector3),this.registerInput("normal",me.Vector3),this.registerInput("center",me.Vector3,!0,D.Zero()),this.registerOutput("uv",me.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}const e=D.Zero(),t=i=>{const r=this.position.getConnectedValue(i)||D.Zero(),n=this.normal.getConnectedValue(i)||D.Zero(),a=this.center.getConnectedValue(i),o=we.Zero();switch(this.mapping){case Vm.Spherical:{r.subtractToRef(a,e);const l=e.length();l>0&&(o.x=Math.acos(e.y/l)/Math.PI,(e.x!==0||e.z!==0)&&(o.y=Math.atan2(e.x,e.z)/(Math.PI*2)));break}case Vm.Cylindrical:{r.subtractToRef(a,e);const l=e.length();l>0&&(o.x=Math.atan2(e.x/l,e.z/l)/(Math.PI*2),o.y=(e.y+1)/2);break}case Vm.Cubic:{const l=Math.abs(n.x),c=Math.abs(n.y),u=Math.abs(n.z),h=Math.max(Math.abs(r.x),Math.abs(r.y),Math.abs(r.z));let d=0,f=0;l>=c&&l>=u?(d=r.y/h-a.y,f=r.z/h-a.z):c>=l&&c>=u?(d=r.x/h-a.x,f=r.z/h-a.z):(d=r.x/h-a.x,f=r.y/h-a.y),o.x=(d+1)/2,o.y=(f+1)/2}}return o};this.uv._storedFunction=i=>t(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Vm[this.mapping]}; `}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}F([Jt("Mapping",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Vm.Spherical},{label:"Cylindrical",value:Vm.Cylindrical},{label:"Cubic",value:Vm.Cubic}]})],D_e.prototype,"mapping",void 0);ve("BABYLON.MappingBlock",D_e);class Kje extends Ri{constructor(e){super(e),this.registerInput("matrix0",me.Matrix),this.registerInput("matrix1",me.Matrix),this.registerOutput("output",me.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return!t||!i?null:t.multiply(i)}}}ve("BABYLON.MatrixComposeBlock",Kje);class Hje extends Ri{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",me.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)t.indexOf(r)===-1&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=t=>this.input.getConnectedValue(t)}}ve("BABYLON.TeleportInBlock",Hje);class jje extends Ri{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",me.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&t.indexOf(this.entryPoint)===-1&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); `),e}serialize(){var t;const e=super.serialize();return e.entryPoint=((t=this.entryPoint)==null?void 0:t.uniqueId)??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}ve("BABYLON.TeleportOutBlock",jje);class L_e extends Ri{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",me.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{const r=new Image,n=document.createElement("canvas"),a=n.getContext("2d");r.onload=()=>{n.width=r.width,n.height=r.height,a.drawImage(r,0,0);const l=a.getImageData(0,0,r.width,r.height).data,c=new Float32Array(l.length);for(let u=0;u{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}const r=e.getSize();Lke.GetTextureDataAsync(e,r.width,r.height).then(async n=>{const a=new Float32Array(n.length);for(let o=0;o=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=t=>{const i=this.texture.getConnectedValue(t);if(!i||!i.data)return null;const r=this.coordinates.getConnectedValue(t);if(!r)return null;const n=this.clampCoordinates?Math.max(0,Math.min(r.x,1)):this._repeatClamp(r.x),a=this.clampCoordinates?Math.max(0,Math.min(r.y,1)):this._repeatClamp(r.y),o=Math.floor(n*(i.width-1)),l=Math.floor(a*(i.height-1)),c=o+i.width*l;return mt.FromArray(i.data,c*4)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; `}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}F([Jt("Clamp Coordinates",0,"ADVANCED",{notifiers:{rebuild:!0}})],O_e.prototype,"clampCoordinates",void 0);ve("BABYLON.GeometryTextureFetchBlock",O_e);class Xje extends Ri{constructor(e){super(e),this.registerInput("geometry",me.Geometry),this.registerOutput("min",me.Vector3),this.registerOutput("max",me.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?JS(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?JS(t.positions,0,t.positions.length/3).maximum:null}}}ve("BABYLON.BoundingBlock",Xje);var Gm;(function(s){s[s.Intersect=0]="Intersect",s[s.Subtract=1]="Subtract",s[s.Union=2]="Union"})(Gm||(Gm={}));class Nee extends Ri{constructor(e){super(e),this.evaluateContext=!1,this.operation=Gm.Intersect,this.registerInput("geometry0",me.Geometry),this.registerInput("geometry1",me.Geometry),this.registerOutput("output",me.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{const r=this.geometry0.getConnectedValue(i),n=this.geometry1.getConnectedValue(i);if(!r||!n)return null;const a=r.positions.length/3;!r.normals&&n.normals&&(r.normals=new Array(r.positions.length)),!n.normals&&r.normals&&(n.normals=new Array(n.positions.length)),!r.uvs&&n.uvs&&(r.uvs=new Array(a*2)),!n.uvs&&r.uvs&&(n.uvs=new Array(a*2)),!r.colors&&n.colors&&(r.colors=new Array(a*4)),!n.colors&&r.colors&&(n.colors=new Array(a*4));const o=Om.FromVertexData(r),l=Om.FromVertexData(n);let c;switch(this.operation){case Gm.Intersect:c=o.intersect(l);break;case Gm.Subtract:c=o.subtract(l);break;case Gm.Union:c=o.union(l);break}return c.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; `;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${Gm[this.operation]}; `,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}F([Jt("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Nee.prototype,"evaluateContext",void 0);F([Jt("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:Gm.Intersect},{label:"Subtract",value:Gm.Subtract},{label:"Union",value:Gm.Union}]})],Nee.prototype,"operation",void 0);ve("BABYLON.BooleanGeometryBlock",Nee);class Yje extends Ri{constructor(e){super(e),this.registerInput("x",me.AutoDetect),this.registerInput("y",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>Math.atan2(t,i);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),r=this.y.getConnectedValue(t);switch(this.x.type){case me.Int:case me.Float:return e(i,r);case me.Vector2:return new we(e(i.x,r.x),e(i.y,r.y));case me.Vector3:return new D(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case me.Vector4:return new mt(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0}}}ve("BABYLON.GeometryArcTan2Block",Yje);class Qje extends Ri{constructor(e){super(e),this.registerInput("left",me.AutoDetect),this.registerInput("right",me.AutoDetect),this.registerInput("gradient",me.Float),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,r)=>(1-t)*i+t*r;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),n=this.gradient.getConnectedValue(t);switch(this.left.type){case me.Int:case me.Float:return e(n,i,r);case me.Vector2:return new we(e(n,i.x,r.x),e(n,i.y,r.y));case me.Vector3:return new D(e(n,i.x,r.x),e(n,i.y,r.y),e(n,i.z,r.z));case me.Vector4:return new mt(e(n,i.x,r.x),e(n,i.y,r.y),e(n,i.z,r.z),e(n,i.w,r.w))}return 0},this}}ve("BABYLON.GeometryLerpBlock",Qje);class $je extends Ri{constructor(e){super(e),this.registerInput("left",me.AutoDetect),this.registerInput("right",me.AutoDetect),this.registerInput("gradient",me.Float),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,r)=>(1-t)*i+t*r;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),n=this.gradient.getConnectedValue(t);switch(this.left.type){case me.Int:case me.Float:return e(n,i,r);case me.Vector2:{const a=new we(e(n,i.x,r.x),e(n,i.y,r.y));return a.normalize(),a}case me.Vector3:{const a=new D(e(n,i.x,r.x),e(n,i.y,r.y),e(n,i.z,r.z));return a.normalize(),a}case me.Vector4:{const a=new mt(e(n,i.x,r.x),e(n,i.y,r.y),e(n,i.z,r.z),e(n,i.w,r.w));return a.normalize(),a}}return 0},this}}ve("BABYLON.GeometryNLerpBlock",$je);class Zje extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerInput("edge",me.Float),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>t{const i=this.value.getConnectedValue(t),r=this.edge.getConnectedValue(t);switch(this.value.type){case me.Int:case me.Float:return e(i,r);case me.Vector2:return new we(e(i.x,r),e(i.y,r));case me.Vector3:return new D(e(i.x,r),e(i.y,r),e(i.z,r));case me.Vector4:return new mt(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}ve("BABYLON.GeometryStepBlock",Zje);class qje extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerInput("edge0",me.Float),this.registerInput("edge1",me.Float),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,r)=>{const n=Math.max(0,Math.min((t-i)/(r-i),1));return n*n*(3-2*n)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.edge0.getConnectedValue(t),n=this.edge1.getConnectedValue(t);switch(this.value.type){case me.Int:case me.Float:return e(i,r,n);case me.Vector2:return new we(e(i.x,r,n),e(i.y,r,n));case me.Vector3:return new D(e(i.x,r,n),e(i.y,r,n),e(i.z,r,n));case me.Vector4:return new mt(e(i.x,r,n),e(i.y,r,n),e(i.z,r,n),e(i.w,r,n))}return 0},this}}ve("BABYLON.GeometrySmoothStepBlock",qje);class Jje extends Ri{constructor(e){super(e),this.registerInput("left",me.AutoDetect),this.registerInput("right",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>t-Math.floor(t/i)*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t);switch(this.left.type){case me.Int:case me.Float:return e(i,r);case me.Vector2:return new we(e(i.x,r.x),e(i.y,r.y));case me.Vector3:return new D(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case me.Vector4:return new mt(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0},this}}ve("BABYLON.GeometryModBlock",Jje);class eXe extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerInput("power",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>Math.pow(t,i);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.power.getConnectedValue(t);switch(this.value.type){case me.Int:case me.Float:return e(i,r);case me.Vector2:return new we(e(i.x,r),e(i.y,r));case me.Vector3:return new D(e(i.x,r),e(i.y,r),e(i.z,r));case me.Vector4:return new mt(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}ve("BABYLON.GeometryPowBlock",eXe);class Fee extends Ri{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Geometry),this._inputs[0].excludedConnectionPointTypes.push(me.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=t=>Math.max(this.minimum,Math.min(t,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case me.Int:case me.Float:return e(i);case me.Vector2:return new we(e(i.x),e(i.y));case me.Vector3:return new D(e(i.x),e(i.y),e(i.z));case me.Vector4:return new mt(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; `;return e+=`${this._codeVariableName}.maximum = ${this.maximum}; `,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}F([Jt("Minimum",1)],Fee.prototype,"minimum",void 0);F([Jt("Maximum",1)],Fee.prototype,"maximum",void 0);ve("BABYLON.GeometryClampBlock",Fee);class tXe extends Ri{constructor(e){super(e),this.registerInput("left",me.AutoDetect),this.registerInput("right",me.AutoDetect),this.registerOutput("output",me.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Int),this._inputs[0].excludedConnectionPointTypes.push(me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Vector2),this._inputs[1].excludedConnectionPointTypes.push(me.Int),this._inputs[1].excludedConnectionPointTypes.push(me.Float),this._inputs[1].excludedConnectionPointTypes.push(me.Matrix),this._inputs[1].excludedConnectionPointTypes.push(me.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case me.Vector3:return D.Cross(t,i);case me.Vector4:return D.Cross(t.toVector3(),i.toVector3())}return 0},this}}ve("BABYLON.GeometryCrossBlock",tXe);var gr;(function(s){s[s.EaseInSine=0]="EaseInSine",s[s.EaseOutSine=1]="EaseOutSine",s[s.EaseInOutSine=2]="EaseInOutSine",s[s.EaseInQuad=3]="EaseInQuad",s[s.EaseOutQuad=4]="EaseOutQuad",s[s.EaseInOutQuad=5]="EaseInOutQuad",s[s.EaseInCubic=6]="EaseInCubic",s[s.EaseOutCubic=7]="EaseOutCubic",s[s.EaseInOutCubic=8]="EaseInOutCubic",s[s.EaseInQuart=9]="EaseInQuart",s[s.EaseOutQuart=10]="EaseOutQuart",s[s.EaseInOutQuart=11]="EaseInOutQuart",s[s.EaseInQuint=12]="EaseInQuint",s[s.EaseOutQuint=13]="EaseOutQuint",s[s.EaseInOutQuint=14]="EaseInOutQuint",s[s.EaseInExpo=15]="EaseInExpo",s[s.EaseOutExpo=16]="EaseOutExpo",s[s.EaseInOutExpo=17]="EaseInOutExpo",s[s.EaseInCirc=18]="EaseInCirc",s[s.EaseOutCirc=19]="EaseOutCirc",s[s.EaseInOutCirc=20]="EaseInOutCirc",s[s.EaseInBack=21]="EaseInBack",s[s.EaseOutBack=22]="EaseOutBack",s[s.EaseInOutBack=23]="EaseInOutBack",s[s.EaseInElastic=24]="EaseInElastic",s[s.EaseOutElastic=25]="EaseOutElastic",s[s.EaseInOutElastic=26]="EaseInOutElastic"})(gr||(gr={}));class N_e extends Ri{constructor(e){super(e),this.type=gr.EaseInOutSine,this.registerInput("input",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[0].excludedConnectionPointTypes.push(me.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let e;switch(this.type){case gr.EaseInSine:e=t=>1-Math.cos(t*3.1415/2);break;case gr.EaseOutSine:e=t=>Math.sin(t*3.1415/2);break;case gr.EaseInOutSine:e=t=>-(Math.cos(t*3.1415)-1)/2;break;case gr.EaseInQuad:e=t=>t*t;break;case gr.EaseOutQuad:e=t=>(1-t)*(1-t);break;case gr.EaseInOutQuad:{e=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break}case gr.EaseInCubic:e=t=>t*t*t;break;case gr.EaseOutCubic:{e=t=>1-Math.pow(1-t,3);break}case gr.EaseInOutCubic:{e=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;break}case gr.EaseInQuart:e=t=>t*t*t*t;break;case gr.EaseOutQuart:{e=t=>1-Math.pow(1-t,4);break}case gr.EaseInOutQuart:{e=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;break}case gr.EaseInQuint:e=t=>t*t*t*t*t;break;case gr.EaseOutQuint:{e=t=>1-Math.pow(1-t,5);break}case gr.EaseInOutQuint:{e=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;break}case gr.EaseInExpo:{e=t=>t===0?0:Math.pow(2,10*t-10);break}case gr.EaseOutExpo:{e=t=>t===1?1:1-Math.pow(2,-10*t);break}case gr.EaseInOutExpo:{e=t=>t===0?0:t===1?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2;break}case gr.EaseInCirc:{e=t=>1-Math.sqrt(1-Math.pow(t,2));break}case gr.EaseOutCirc:{e=t=>Math.sqrt(1-Math.pow(t-1,2));break}case gr.EaseInOutCirc:{e=t=>t<.5?(1-Math.sqrt(1-Math.pow(2*t,2)))/2:(Math.sqrt(1-Math.pow(-2*t+2,2))+1)/2;break}case gr.EaseInBack:{e=t=>2.70158*t*t*t-1.70158*t*t;break}case gr.EaseOutBack:{e=t=>2.70158*Math.pow(t-1,3)+1.70158*Math.pow(t-1,2);break}case gr.EaseInOutBack:{e=t=>t<.5?Math.pow(2*t,2)*(3.5949095*2*t-2.5949095)/2:(Math.pow(2*t-2,2)*(3.5949095*(t*2-2)+3.5949095)+2)/2;break}case gr.EaseInElastic:{e=t=>t===0?0:t===1?1:-Math.pow(2,10*t-10)*Math.sin((t*10-10.75)*(2*3.1415/3));break}case gr.EaseOutElastic:{e=t=>t===0?0:t===1?1:Math.pow(2,-10*t)*Math.sin((t*10-.75)*(2*3.1415/3))+1;break}case gr.EaseInOutElastic:{e=t=>t===0?0:t==1?1:t<.5?-(Math.pow(2,20*t-10)*Math.sin((20*t-11.125)*(2*3.1415/4.5)))/2:Math.pow(2,-20*t+10)*Math.sin((20*t-11.125)*(2*3.1415/4.5))/2+1;break}}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case me.Float:return e(i);case me.Vector2:return new we(e(i.x),e(i.y));case me.Vector3:return new D(e(i.x),e(i.y),e(i.z));case me.Vector4:return new mt(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${gr[this.type]}; `}}F([Jt("Type",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:gr.EaseInSine},{label:"EaseOutSine",value:gr.EaseOutSine},{label:"EaseInOutSine",value:gr.EaseInOutSine},{label:"EaseInQuad",value:gr.EaseInQuad},{label:"EaseOutQuad",value:gr.EaseOutQuad},{label:"EaseInOutQuad",value:gr.EaseInOutQuad},{label:"EaseInCubic",value:gr.EaseInCubic},{label:"EaseOutCubic",value:gr.EaseOutCubic},{label:"EaseInOutCubic",value:gr.EaseInOutCubic},{label:"EaseInQuart",value:gr.EaseInQuart},{label:"EaseOutQuart",value:gr.EaseOutQuart},{label:"EaseInOutQuart",value:gr.EaseInOutQuart},{label:"EaseInQuint",value:gr.EaseInQuint},{label:"EaseOutQuint",value:gr.EaseOutQuint},{label:"EaseInOutQuint",value:gr.EaseInOutQuint},{label:"EaseInExpo",value:gr.EaseInExpo},{label:"EaseOutExpo",value:gr.EaseOutExpo},{label:"EaseInOutExpo",value:gr.EaseInOutExpo},{label:"EaseInCirc",value:gr.EaseInCirc},{label:"EaseOutCirc",value:gr.EaseOutCirc},{label:"EaseInOutCirc",value:gr.EaseInOutCirc},{label:"EaseInBack",value:gr.EaseInBack},{label:"EaseOutBack",value:gr.EaseOutBack},{label:"EaseInOutBack",value:gr.EaseInOutBack},{label:"EaseInElastic",value:gr.EaseInElastic},{label:"EaseOutElastic",value:gr.EaseOutElastic},{label:"EaseInOutElastic",value:gr.EaseInOutElastic}]})],N_e.prototype,"type",void 0);ve("BABYLON.GeometryCurveBlock",N_e);class iXe extends Ri{constructor(e){super(e),this.registerInput("color",me.Vector3),this.registerInput("level",me.Float,!0,0),this.registerOutput("output",me.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.color.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),r=Math.min(t.x,t.y,t.z),n=Math.max(t.x,t.y,t.z),a=.5*(r+n);return new D(t.x*(1-i)+a*i,t.y*(1-i)+a*i,t.z*(1-i)+a*i)},this}}ve("BABYLON.GeometryDesaturateBlock",iXe);class rXe extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerInput("steps",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[1].excludedConnectionPointTypes.push(me.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(me.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.steps.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let r=i;if(this.steps.type===me.Float)switch(this.value.type){case me.Vector2:r=new we(i,i);break;case me.Vector3:r=new D(i,i,i);break;case me.Vector4:r=new mt(i,i,i,i);break}switch(this.value.type){case me.Vector2:return new we(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y));case me.Vector3:return new D(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z));case me.Vector4:return new mt(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z),t.w/(1/r.w)*(1/r.w));default:return Math.floor(t/(1/i)*(1/i))}},this}}ve("BABYLON.GeometryPosterizeBlock",rXe);class sXe extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerInput("reference",me.AutoDetect),this.registerInput("distance",me.Float),this.registerInput("replacement",me.AutoDetect),this.registerOutput("output",me.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[1].excludedConnectionPointTypes.push(me.Float),this._inputs[1].excludedConnectionPointTypes.push(me.Matrix),this._inputs[3].excludedConnectionPointTypes.push(me.Float),this._inputs[3].excludedConnectionPointTypes.push(me.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.reference.isConnected||!this.distance.isConnected||!this.replacement.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),r=this.distance.getConnectedValue(e),n=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this}}ve("BABYLON.GeometryDistanceBlock",nXe);class aXe extends Ri{constructor(e){super(e),this.registerInput("left",me.AutoDetect),this.registerInput("right",me.AutoDetect),this.registerOutput("output",me.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(me.Int),this._inputs[0].excludedConnectionPointTypes.push(me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix),this._inputs[1].excludedConnectionPointTypes.push(me.Float),this._inputs[1].excludedConnectionPointTypes.push(me.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this}}ve("BABYLON.GeometryDotBlock",aXe);class oXe extends Ri{constructor(e){super(e),this.registerInput("value",me.AutoDetect),this.registerOutput("output",me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Int),this._inputs[0].excludedConnectionPointTypes.push(me.Float),this._inputs[0].excludedConnectionPointTypes.push(me.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this}}ve("BABYLON.GeometryLengthBlock",oXe);class lXe extends Ri{constructor(e){super(e),this.registerInput("input",me.Vector2),this.registerInput("angle",me.Float),this.registerOutput("output",me.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.angle.isConnected||!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new we(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this}}ve("BABYLON.GeometryRotate2dBlock",lXe);class Cv extends Ee{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=he.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._splatPositions=null;const r=new at;r.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],r.indices=[0,1,2,0,2,3],r.applyToMesh(this),this.subMeshes=[],new wl(0,0,4,0,6,this),this.setEnabled(!1),this._lastModelViewMatrix=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new uw(this.name+"_material",this._scene),this.material=this._material);const r=this.getScene().getFrameId();if(r!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix),se.Vector3[0].set(this._lastModelViewMatrix[8],this._lastModelViewMatrix[9],this._lastModelViewMatrix[10]),se.Vector3[1].set(this._modelViewMatrix.m[8],this._modelViewMatrix.m[9],this._modelViewMatrix.m[10]),se.Vector3[0].normalize(),se.Vector3[1].normalize();const n=D.Dot(se.Vector3[0],se.Vector3[1]);Math.abs(n-1)>=.01&&(this._frameIdLastUpdate=r,this._canPostToWorker=!1,this._lastModelViewMatrix=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=new TextDecoder().decode(t.slice(0,1024*10)),r=`end_header `,n=i.indexOf(r);if(n<0||!i)return e;const a=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let o=0;const l={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},c=[],u=i.slice(0,n).split(` `).filter(g=>g.startsWith("property "));for(const g of u){const[,_,y]=g.split(" ");if(c.push({name:y,type:_,offset:o}),l[_])o+=l[_];else return fe.Error(`Unsupported property type: ${_}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0)}const h=3*4+3*4+4+4,d=.28209479177387814,f=new DataView(e,n+r.length),p=new ArrayBuffer(h*a),m=new Pe;for(let g=0;g{this._loadData(Cv.ConvertPLYToSplat(t))})}dispose(e){var t,i,r,n,a,o;(t=this._covariancesATexture)==null||t.dispose(),(i=this._covariancesBTexture)==null||i.dispose(),(r=this._centersTexture)==null||r.dispose(),(n=this._colorsTexture)==null||n.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,(a=this._material)==null||a.dispose(!1,!0),this._material=null,(o=this._worker)==null||o.terminate(),this._worker=null,super.dispose(e)}_copyTextures(e){var t,i,r,n;this._covariancesATexture=(t=e.covariancesATexture)==null?void 0:t.clone(),this._covariancesBTexture=(i=e.covariancesBTexture)==null?void 0:i.clone(),this._centersTexture=(r=e.centersTexture)==null?void 0:r.clone(),this._colorsTexture=(n=e.colorsTexture)==null?void 0:n.clone()}clone(e=""){const t=new Cv(e,void 0,this.getScene());t._copySource(this),t.makeGeometryUnique(),t._vertexCount=this._vertexCount,t._copyTextures(this),t._modelViewMatrix=he.Identity(),t._splatPositions=this._splatPositions,t._instanciateWorker();const i=this.getBoundingInfo();return t.getBoundingInfo().reConstruct(i.minimum,i.maximum,this.getWorldMatrix()),t.forcedInstanceCount=t._vertexCount,t.setEnabled(!0),t}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),r=3*4+3*4+4+4,n=t.length/r;this._vertexCount=n;const a=this._getTextureSize(n),o=a.x*a.y;this._splatPositions=new Float32Array(3*o);const l=new Float32Array(3*o),c=new Float32Array(3*o),u=se.Matrix[0],h=se.Matrix[1],d=se.Quaternion[0],f=new D(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),p=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let v=0;vnew yn(v,x,A,b,this._scene,!1,!1,2,1),_=v=>{const x=v.length/3,A=new Float32Array(x*4);for(let b=0;b{this._depthMix=n.data.depthMix;const a=new Uint32Array(n.data.depthMix.buffer);for(let o=0;oi&&(fe.Error("GaussianSplatting texture size: ("+i+", "+r+"), maxTextureSize: "+i),r=i),new we(i,r)}}Cv._CreateWorker=function(s){let e=0,t,i,r,n;s.onmessage=a=>{if(a.data.positions)t=a.data.positions,e=a.data.vertexCount;else{const o=a.data.view;if(!t||!o)throw new Error("positions or view is not defined!");i=a.data.depthMix,r=new Uint32Array(i.buffer),n=new Float32Array(i.buffer);for(let c=0;c #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) fragmentOutputs.color=input.vColor; #else fragmentOutputs.color=uniforms.color; #endif #include(color,fragmentOutputs.color) #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[cXe]=uXe;const hXe={name:cXe,shader:uXe},vMt=Object.freeze(Object.defineProperty({__proto__:null,colorPixelShaderWGSL:hXe},Symbol.toStringTag,{value:"Module"})),dXe="colorVertexShader",fXe=`attribute position: vec3f; #ifdef VERTEXCOLOR attribute color: vec4f; #endif #include #include #include #include #ifdef FOG uniform view: mat4x4f; #endif #include uniform viewProjection: mat4x4f; #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN #include #include #include var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; #include #include #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[dXe]=fXe;const pXe={name:dXe,shader:fXe},yMt=Object.freeze(Object.defineProperty({__proto__:null,colorVertexShaderWGSL:pXe},Symbol.toStringTag,{value:"Module"})),mXe="meshUVSpaceRendererVertexShader",gXe=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; #include #include #include #include[0..maxSimultaneousMorphTargets] #include void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif vNormalW=normalize(normWorldSM*normalUpdated); #endif vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`;de.ShadersStore[mXe]=gXe;const _Xe={name:mXe,shader:gXe},xMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererVertexShader:_Xe},Symbol.toStringTag,{value:"Module"})),vXe="meshUVSpaceRendererPixelShader",yXe=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} gl_FragColor=texture2D(textureSampler,vDecalTC);} `;de.ShadersStore[vXe]=yXe;const xXe={name:vXe,shader:yXe},AMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererPixelShader:xXe},Symbol.toStringTag,{value:"Module"})),AXe="meshUVSpaceRendererMaskerVertexShader",bXe="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";de.ShadersStore[AXe]=bXe;const CXe={name:AXe,shader:bXe},bMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerVertexShader:CXe},Symbol.toStringTag,{value:"Module"})),SXe="meshUVSpaceRendererMaskerPixelShader",EXe=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} `;de.ShadersStore[SXe]=EXe;const TXe={name:SXe,shader:EXe},CMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerPixelShader:TXe},Symbol.toStringTag,{value:"Module"})),MXe="meshUVSpaceRendererFinaliserPixelShader",RXe=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;} if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;} if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;} if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;} if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}} `;de.ShadersStore[MXe]=RXe;const IXe={name:MXe,shader:RXe},SMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserPixelShader:IXe},Symbol.toStringTag,{value:"Module"})),PXe="meshUVSpaceRendererFinaliserVertexShader",wXe=`precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;} `;de.ShadersStore[PXe]=wXe;const DXe={name:PXe,shader:wXe},EMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserVertexShader:DXe},Symbol.toStringTag,{value:"Module"})),LXe="meshUVSpaceRendererVertexShader",OXe=`attribute position: vec3f;attribute normal: vec3f;attribute uv: vec2f;uniform projMatrix: mat4x4f;varying vDecalTC: vec2f; #include #include #include #include[0..maxSimultaneousMorphTargets] #include @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal; #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);var vNormalW: vec3f; #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif vNormalW=normalize(normWorldSM*normalUpdated); #endif var normalView: vec3f=normalize((uniforms.projMatrix* vec4f(vNormalW,0.0)).xyz);var decalTC: vec3f=(uniforms.projMatrix*worldPos).xyz;vertexOutputs.vDecalTC=decalTC.xy;vertexOutputs.position=vec4f(input.uv*2.0-1.0,select(decalTC.z,2.,normalView.z>0.0),1.0);}`;de.ShadersStoreWGSL[LXe]=OXe;const NXe={name:LXe,shader:OXe},TMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererVertexShaderWGSL:NXe},Symbol.toStringTag,{value:"Module"})),FXe="meshUVSpaceRendererPixelShader",BXe=`varying vDecalTC: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;@fragment fn main(input: FragmentInputs)->FragmentOutputs {if (input.vDecalTC.x<0. || input.vDecalTC.x>1. || input.vDecalTC.y<0. || input.vDecalTC.y>1.) {discard;} fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vDecalTC);} `;de.ShadersStoreWGSL[FXe]=BXe;const kXe={name:FXe,shader:BXe},MMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererPixelShaderWGSL:kXe},Symbol.toStringTag,{value:"Module"})),UXe="meshUVSpaceRendererMaskerVertexShader",zXe=`attribute uv: vec2f;varying vUV: vec2f;@vertex fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position= vec4f( vec2f(input.uv.x,input.uv.y)*2.0-1.0,0.,1.0);vertexOutputs.vUV=input.uv;}`;de.ShadersStoreWGSL[UXe]=zXe;const VXe={name:UXe,shader:zXe},RMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerVertexShaderWGSL:VXe},Symbol.toStringTag,{value:"Module"})),GXe="meshUVSpaceRendererMaskerPixelShader",WXe=`varying vUV: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color= vec4f(1.0,1.0,1.0,1.0);} `;de.ShadersStoreWGSL[GXe]=WXe;const KXe={name:GXe,shader:WXe},IMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerPixelShaderWGSL:KXe},Symbol.toStringTag,{value:"Module"})),HXe="meshUVSpaceRendererFinaliserPixelShader",jXe=`#define DISABLE_UNIFORMITY_ANALYSIS varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var maskTextureSamplerSampler: sampler;var maskTextureSampler: texture_2d;uniform textureSize: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {var mask: vec4f=textureSample(maskTextureSampler,maskTextureSamplerSampler,input.vUV).rgba;if (mask.r>0.5) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);} else {var texelSize: vec2f=4.0/uniforms.textureSize;var uv_p01: vec2f=input.vUV+ vec2f(-1.0,0.0)*texelSize;var uv_p21: vec2f=input.vUV+ vec2f(1.0,0.0)*texelSize;var uv_p10: vec2f=input.vUV+ vec2f(0.0,-1.0)*texelSize;var uv_p12: vec2f=input.vUV+ vec2f(0.0,1.0)*texelSize;var mask_p01: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p01).r;var mask_p21: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p21).r;var mask_p10: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p10).r;var mask_p12: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p12).r;var col: vec4f= vec4f(0.0,0.0,0.0,0.0);var total_weight: f32=0.0;if (mask_p01>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p01);total_weight+=1.0;} if (mask_p21>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p21);total_weight+=1.0;} if (mask_p10>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p10);total_weight+=1.0;} if (mask_p12>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p12);total_weight+=1.0;} if (total_weight>0.0) {fragmentOutputs.color=col/total_weight;} else {fragmentOutputs.color=col;}}} `;de.ShadersStoreWGSL[HXe]=jXe;const XXe={name:HXe,shader:jXe},PMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserPixelShaderWGSL:XXe},Symbol.toStringTag,{value:"Module"})),YXe="meshUVSpaceRendererFinaliserVertexShader",QXe=`attribute position: vec3f;attribute uv: vec2f;uniform worldViewProjection: mat4x4f;varying vUV: vec2f;@vertex fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.worldViewProjection* vec4f(input.position,1.0);vertexOutputs.positionvUV=input.uv;} `;de.ShadersStoreWGSL[YXe]=QXe;const $Xe={name:YXe,shader:QXe},wMt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserVertexShaderWGSL:$Xe},Symbol.toStringTag,{value:"Module"}));class DMt{constructor(e=Recast){if(this.bjsRECAST={},this.name="RecastJSPlugin",this._maximumSubStepCount=10,this._timeStep=1/60,this._timeFactor=1,this._worker=null,typeof e=="function"?fe.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,!this.isSupported()){fe.Error("RecastJS is not available. Please make sure you included the js file.");return}this.setTimeStep(),this._tempVec1=new this.bjsRECAST.Vec3,this._tempVec2=new this.bjsRECAST.Vec3}setWorkerURL(e){return window&&window.Worker?(this._worker=new Worker(e),!0):!1}setTimeStep(e=1/60){this._timeStep=e}getTimeStep(){return this._timeStep}setMaximumSubStepCount(e=10){this._maximumSubStepCount=e}getMaximumSubStepCount(){return this._maximumSubStepCount}set timeFactor(e){this._timeFactor=Math.max(e,0)}get timeFactor(){return this._timeFactor}createNavMesh(e,t,i){this._worker&&!i?fe.Warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&fe.Warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;let r,n,a;const o=[],l=[];let c=0;for(r=0;r{this.update(r.getEngine().getDeltaTime()*.001*e.timeFactor)})}addAgent(e,t,i){const r=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;r.radius=t.radius,r.height=t.height,r.maxAcceleration=t.maxAcceleration,r.maxSpeed=t.maxSpeed,r.collisionQueryRange=t.collisionQueryRange,r.pathOptimizationRange=t.pathOptimizationRange,r.separationWeight=t.separationWeight,r.updateFlags=7,r.obstacleAvoidanceType=0,r.queryFilterType=0,r.userData=0;const n=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),r);return this.transforms.push(i),this.agents.push(n),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new D(0,0,0)),n}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new D(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new D(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new D(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);t.radius!==void 0&&(i.radius=t.radius),t.height!==void 0&&(i.height=t.height),t.maxAcceleration!==void 0&&(i.maxAcceleration=t.maxAcceleration),t.maxSpeed!==void 0&&(i.maxSpeed=t.maxSpeed),t.collisionQueryRange!==void 0&&(i.collisionQueryRange=t.collisionQueryRange),t.pathOptimizationRange!==void 0&&(i.pathOptimizationRange=t.pathOptimizationRange),t.separationWeight!==void 0&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=ci)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=ci)this.recastCrowd.update(e);else{let r=Math.floor(e/t);i&&r>i&&(r=i),r<1&&(r=1);const n=e/r;for(let a=0;au&&a.ynew Ru(s,e,t);class Ru{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory=typeof indexedDB<"u"?indexedDB:void 0,this._currentSceneUrl=Ru._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Ru.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Me.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if(typeof URL=="function"&&this._currentSceneUrl.indexOf("http")===0){const o=new URL(this._currentSceneUrl);return o.pathname+=".manifest",o.toString()}}catch{}return`${this._currentSceneUrl}.manifest`};let r=!1,n=i();const a=new On;navigator.onLine&&(r=!0,n=n+(n.match(/\?/)==null?"?":"&")+Date.now()),a.open("GET",n),a.addEventListener("load",()=>{if(a.status===200||Ru._ValidateXHRData(a,1))try{const o=JSON.parse(a.response);this._enableSceneOffline=o.enableSceneOffline,this._enableTexturesOffline=o.enableTexturesOffline&&Ru._IsUASupportingBlobStorage,o.version&&!isNaN(parseInt(o.version))&&(this._manifestVersionFound=o.version),e(!0)}catch{t()}else t()},!1),a.addEventListener("error",()=>{if(r){r=!1;const o=i();a.open("GET",o),a.send()}else t()},!1);try{a.send()}catch{fe.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(!this._idbFactory||!(this._enableSceneOffline||this._enableTexturesOffline))this._isSupported=!1,t&&t();else if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const r=this._idbFactory.open("babylonjs",1);r.onerror=()=>{i()},r.onblocked=()=>{fe.Error("IDB request blocked. Please reload the page."),i()},r.onsuccess=()=>{this._db=r.result,e()},r.onupgradeneeded=n=>{if(this._db=n.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(a){fe.Error("Error while creating object stores. Exception: "+a.message),i()}}}}loadImage(e,t){const i=Ru._ReturnFullUrlLocation(e),r=()=>{!this._hasReachedQuota&&this._db!==null?this._saveImageIntoDBAsync(i,t):t.src=e};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&this._db!==null){let r;const n=this._db.transaction(["textures"]);n.onabort=()=>{t.src=e},n.oncomplete=()=>{let o;r&&typeof URL=="function"?(o=URL.createObjectURL(r.data),t.onerror=()=>{fe.Error("Error loading image from blob URL: "+o+" switching back to web url: "+e),t.src=e},t.src=o):i()};const a=n.objectStore("textures").get(e);a.onsuccess=o=>{r=o.target.result},a.onerror=()=>{fe.Error("Error loading texture "+e+" from DB."),t.src=e}}else fe.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const r=()=>{let n;if(i&&typeof URL=="function")try{n=URL.createObjectURL(i)}catch{n=URL.createObjectURL(i)}n&&(t.src=n)};if(Ru._IsUASupportingBlobStorage){const n=new On;n.open("GET",e),n.responseType="blob",n.addEventListener("load",()=>{if(n.status===200&&this._db){i=n.response;const a=this._db.transaction(["textures"],"readwrite");a.onabort=l=>{try{const u=l.target.error;u&&u.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}r()},a.oncomplete=()=>{r()};const o={textureUrl:e,data:i};try{const l=a.objectStore("textures").put(o);l.onsuccess=()=>{},l.onerror=()=>{r()}}catch(l){l.code===25&&(Ru._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),n.addEventListener("error",()=>{fe.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),n.send()}else t.src=e}else fe.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){const i=()=>{this._saveVersionIntoDBAsync(e,t)};this._loadVersionFromDBAsync(e,t,i)}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{const n=this._db.transaction(["versions"]);n.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},n.onabort=()=>{t(-1)};const a=n.objectStore("versions").get(e);a.onsuccess=o=>{r=o.target.result},a.onerror=()=>{fe.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(n){fe.Error("Error while accessing 'versions' object store (READ OP). Exception: "+n.message),t(-1)}}else fe.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=a=>{try{const o=a.target.error;o&&o.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const r={sceneUrl:e,data:this._manifestVersionFound},n=i.objectStore("versions").put(r);n.onsuccess=()=>{},n.onerror=()=>{fe.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){fe.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,r,n){const a=Ru._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(a,t,i,n,r)};this._checkVersionFromDB(a,l=>{l!==-1?this._mustUpdateRessources?this._saveFileAsync(a,t,i,n,r):this._loadFileAsync(a,t,o,i):r&&r()})}_loadFileAsync(e,t,i,r){if(this._isSupported&&this._db){let n;e.indexOf(".babylon")!==-1?n="scenes":n="textures";let a;const o=this._db.transaction([n]);o.oncomplete=()=>{var c;if(a){if(r){const u=((c=a.data)==null?void 0:c.byteLength)||0;r({total:u,loaded:u,lengthComputable:!0})}t(a.data)}else i()},o.onabort=()=>{i()};const l=o.objectStore(n).get(e);l.onsuccess=c=>{a=c.target.result},l.onerror=()=>{fe.Error("Error loading file "+e+" from DB."),i()}}else fe.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,n){if(this._isSupported){let a;e.indexOf(".babylon")!==-1?a="scenes":a="textures";const o=new On;let l;o.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(o.status===200||o.status<400&&Ru._ValidateXHRData(o,r?6:1))if(l=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){const c=this._db.transaction([a],"readwrite");c.onabort=h=>{try{const d=h.target.error;d&&d.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(l)},c.oncomplete=()=>{t(l)};let u;a==="scenes"?u={sceneUrl:e,data:l,version:this._manifestVersionFound}:u={textureUrl:e,data:l};try{const h=c.objectStore(a).put(u);h.onsuccess=()=>{},h.onerror=()=>{fe.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else o.status>=400&&n?n(o):t()},!1),o.addEventListener("error",()=>{fe.Error("error on XHR request."),n&&n()},!1),o.send()}else fe.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),n&&n()}static _ValidateXHRData(e,t=7){try{if(t&1){if(e.responseText&&e.responseText.length>0)return!0;if(t===1)return!1}if(t&2){const i=Yz(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(t===2)return!1}if(t&4){const i=new Uint8Array(e.response,0,3);return i[0]===68&&i[1]===68&&i[2]===83}}catch{}return!1}}Ru._IsUASupportingBlobStorage=!0;Ru.IDBStorageEnabled=!1;Ru._ParseURL=s=>{const e=document.createElement("a");e.href=s;const t=s.substring(0,s.lastIndexOf("#")),i=s.substring(t.lastIndexOf("/")+1,s.length);return s.substring(0,s.indexOf(i,0))};Ru._ReturnFullUrlLocation=s=>s.indexOf("http:/")===-1&&s.indexOf("https:/")===-1&&typeof window<"u"?Ru._ParseURL(window.location.href)+s:s;class Sv{constructor(){this.direction1=new D(0,1,0),this.direction2=new D(0,1,0),this.minEmitBox=new D(-.5,-.5,-.5),this.maxEmitBox=new D(.5,.5,.5)}startDirectionFunction(e,t,i,r){const n=Es(this.direction1.x,this.direction2.x),a=Es(this.direction1.y,this.direction2.y),o=Es(this.direction1.z,this.direction2.z);if(r){t.x=n,t.y=a,t.z=o;return}D.TransformNormalFromFloatsToRef(n,a,o,e,t)}startPositionFunction(e,t,i,r){const n=Es(this.minEmitBox.x,this.maxEmitBox.x),a=Es(this.minEmitBox.y,this.maxEmitBox.y),o=Es(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=n,t.y=a,t.z=o;return}D.TransformCoordinatesFromFloatsToRef(n,a,o,e,t)}clone(){const e=new Sv;return Nl.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){D.FromArrayToRef(e.direction1,0,this.direction1),D.FromArrayToRef(e.direction2,0,this.direction2),D.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),D.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class oD{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){this._angle!==0?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?se.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),se.Vector3[0]).normalize();const n=At.RandomRange(0,this.directionRandomizer),a=At.RandomRange(0,this.directionRandomizer),o=At.RandomRange(0,this.directionRandomizer);t.x=se.Vector3[0].x+n,t.y=se.Vector3[0].y+a,t.z=se.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,r){const n=At.RandomRange(0,Math.PI*2);let a;this.emitFromSpawnPointOnly?a=1e-4:(a=At.RandomRange(0,this.heightRange),a=1-a*a);let o=this._radius-At.RandomRange(0,this._radius*this.radiusRange);o=o*a;const l=o*Math.sin(n),c=o*Math.cos(n),u=a*this._height;if(r){t.x=l,t.y=u,t.z=c;return}D.TransformCoordinatesFromFloatsToRef(l,u,c,e,t)}clone(){const e=new oD(this._radius,this._angle,this.directionRandomizer);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+=` #define CONEEMITTERSPAWNPOINT`),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=e.radiusRange!==void 0?e.radiusRange:1,this.heightRange=e.radiusRange!==void 0?e.heightRange:1,this.emitFromSpawnPointOnly=e.emitFromSpawnPointOnly!==void 0?e.emitFromSpawnPointOnly:!1}}class Jz extends oD{constructor(e=1,t=Math.PI,i=new D(0,1,0),r=new D(0,1,0)){super(e,t),this.direction1=i,this.direction2=r}startDirectionFunction(e,t){const i=At.RandomRange(this.direction1.x,this.direction2.x),r=At.RandomRange(this.direction1.y,this.direction2.y),n=At.RandomRange(this.direction1.z,this.direction2.z);D.TransformNormalFromFloatsToRef(i,r,n,e,t)}clone(){const e=new Jz(this.radius,this.angle,this.direction1,this.direction2);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define CONEEMITTER #define DIRECTEDCONEEMITTER`}getClassName(){return"ConeDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class lD{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=D.Zero()}startDirectionFunction(e,t,i,r,n){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),D.TransformNormalToRef(this._tempVector,n,this._tempVector);const a=At.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);if(o+=At.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=a,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}D.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){const n=At.RandomRange(-this.height/2,this.height/2),a=At.RandomRange(0,2*Math.PI),o=At.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(o)*this.radius,c=l*Math.cos(a),u=l*Math.sin(a);if(r){t.copyFromFloats(c,n,u);return}D.TransformCoordinatesFromFloatsToRef(c,n,u,e,t)}clone(){const e=new lD(this.radius,this.directionRandomizer);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class eV extends lD{constructor(e=1,t=1,i=1,r=new D(0,1,0),n=new D(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=n}startDirectionFunction(e,t,i,r){const n=At.RandomRange(this.direction1.x,this.direction2.x),a=At.RandomRange(this.direction1.y,this.direction2.y),o=At.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(n,a,o);return}D.TransformNormalFromFloatsToRef(n,a,o,e,t)}clone(){const e=new eV(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define CYLINDEREMITTER #define DIRECTEDCYLINDEREMITTER`}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),D.FromArrayToRef(e.direction1,0,this.direction1),D.FromArrayToRef(e.direction2,0,this.direction2)}}class tV{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const n=i.position.subtract(e.getTranslation()).normalize(),a=At.RandomRange(0,this.directionRandomizer),o=At.RandomRange(0,this.directionRandomizer),l=At.RandomRange(0,this.directionRandomizer);if(n.x+=a,n.y+=o,n.z+=l,n.normalize(),r){t.copyFrom(n);return}D.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)}startPositionFunction(e,t,i,r){const n=this.radius-At.RandomRange(0,this.radius*this.radiusRange),a=At.RandomRange(0,1),o=At.RandomRange(0,2*Math.PI),l=Math.acos(2*a-1),c=n*Math.cos(o)*Math.sin(l),u=n*Math.cos(l),h=n*Math.sin(o)*Math.sin(l);if(r){t.copyFromFloats(c,Math.abs(u),h);return}D.TransformCoordinatesFromFloatsToRef(c,Math.abs(u),h,e,t)}clone(){const e=new tV(this.radius,this.directionRandomizer);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class iV{constructor(){this.direction1=new D(0,1,0),this.direction2=new D(0,1,0)}startDirectionFunction(e,t,i,r){const n=At.RandomRange(this.direction1.x,this.direction2.x),a=At.RandomRange(this.direction1.y,this.direction2.y),o=At.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(n,a,o);return}D.TransformNormalFromFloatsToRef(n,a,o,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}D.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new iV;return Nl.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){D.FromArrayToRef(e.direction1,0,this.direction1),D.FromArrayToRef(e.direction2,0,this.direction2)}}class cD{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const n=i.position.subtract(e.getTranslation()).normalize(),a=At.RandomRange(0,this.directionRandomizer),o=At.RandomRange(0,this.directionRandomizer),l=At.RandomRange(0,this.directionRandomizer);if(n.x+=a,n.y+=o,n.z+=l,n.normalize(),r){t.copyFrom(n);return}D.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)}startPositionFunction(e,t,i,r){const n=this.radius-At.RandomRange(0,this.radius*this.radiusRange),a=At.RandomRange(0,1),o=At.RandomRange(0,2*Math.PI),l=Math.acos(2*a-1),c=n*Math.cos(o)*Math.sin(l),u=n*Math.cos(l),h=n*Math.sin(o)*Math.sin(l);if(r){t.copyFromFloats(c,u,h);return}D.TransformCoordinatesFromFloatsToRef(c,u,h,e,t)}clone(){const e=new cD(this.radius,this.directionRandomizer);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class rV extends cD{constructor(e=1,t=new D(0,1,0),i=new D(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=At.RandomRange(this.direction1.x,this.direction2.x),r=At.RandomRange(this.direction1.y,this.direction2.y),n=At.RandomRange(this.direction1.z,this.direction2.z);D.TransformNormalFromFloatsToRef(i,r,n,e,t)}clone(){const e=new rV(this.radius,this.direction1,this.direction2);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define SPHEREEMITTER #define DIRECTEDSPHEREEMITTER`}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class Ev{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){const n=se.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,n);const a=se.Vector3[1];n.subtractToRef(i.position,a),a.scaleToRef(1/i.lifeTime,n)}else n.set(0,0,0);if(r){t.copyFrom(n);return}D.TransformNormalToRef(n,e,t)}startPositionFunction(e,t,i,r){const n=se.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,n):n.set(0,0,0),r){t.copyFrom(n);return}D.TransformCoordinatesToRef(n,e,t)}clone(){const e=new Ev;return Nl.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class Bee{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData($.PositionKind),this._normals=e.getVerticesData($.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=D.Zero(),this._mesh=null,this.direction1=new D(0,1,0),this.direction2=new D(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){D.TransformNormalToRef(this._storedNormal,e,t);return}const n=At.RandomRange(this.direction1.x,this.direction2.x),a=At.RandomRange(this.direction1.y,this.direction2.y),o=At.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(n,a,o);return}D.TransformNormalFromFloatsToRef(n,a,o,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;const n=3*Math.random()*(this._indices.length/3)|0,a=Math.random(),o=Math.random()*(1-a),l=1-a-o,c=this._indices[n],u=this._indices[n+1],h=this._indices[n+2],d=se.Vector3[0],f=se.Vector3[1],p=se.Vector3[2],m=se.Vector3[3];D.FromArrayToRef(this._positions,c*3,d),D.FromArrayToRef(this._positions,u*3,f),D.FromArrayToRef(this._positions,h*3,p),m.x=a*d.x+o*f.x+l*p.x,m.y=a*d.y+o*f.y+l*p.y,m.z=a*d.z+o*f.z+l*p.z,r?t.copyFromFloats(m.x,m.y,m.z):D.TransformCoordinatesFromFloatsToRef(m.x,m.y,m.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(D.FromArrayToRef(this._normals,c*3,d),D.FromArrayToRef(this._normals,u*3,f),D.FromArrayToRef(this._normals,h*3,p),this._storedNormal.x=a*d.x+o*f.x+l*p.x,this._storedNormal.y=a*d.y+o*f.y+l*p.y,this._storedNormal.z=a*d.z+o*f.z+l*p.z)}clone(){const e=new Bee(this.mesh);return Nl.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var t;const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=(t=this.mesh)==null?void 0:t.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){D.FromArrayToRef(e.direction1,0,this.direction1),D.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class qXe{_isUbo(e){return e.addUniform!==void 0}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}const LMt="gpuUpdateParticlesPixelShader",OMt=`#version 300 es void main() {discard;} `;de.ShadersStore[LMt]=OMt;const NMt="gpuUpdateParticlesVertexShader",FMt=`#version 300 es #define PI 3.14159 uniform float currentCount;uniform float timeDelta;uniform float stopFactor; #ifndef LOCAL uniform mat4 emitterWM; #endif uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; #ifndef COLORGRADIENTS uniform vec4 color1;uniform vec4 color2; #endif uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; #ifdef BOXEMITTER uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; #endif #ifdef POINTEMITTER uniform vec3 direction1;uniform vec3 direction2; #endif #ifdef HEMISPHERICEMITTER uniform float radius;uniform float radiusRange;uniform float directionRandomizer; #endif #ifdef SPHEREEMITTER uniform float radius;uniform float radiusRange; #ifdef DIRECTEDSPHEREEMITTER uniform vec3 direction1;uniform vec3 direction2; #else uniform float directionRandomizer; #endif #endif #ifdef CYLINDEREMITTER uniform float radius;uniform float height;uniform float radiusRange; #ifdef DIRECTEDCYLINDEREMITTER uniform vec3 direction1;uniform vec3 direction2; #else uniform float directionRandomizer; #endif #endif #ifdef CONEEMITTER uniform vec2 radius;uniform float coneAngle;uniform vec2 height; #ifdef DIRECTEDCONEEMITTER uniform vec3 direction1;uniform vec3 direction2; #else uniform float directionRandomizer; #endif #endif in vec3 position; #ifdef CUSTOMEMITTER in vec3 initialPosition; #endif in float age;in float life;in vec4 seed;in vec3 size; #ifndef COLORGRADIENTS in vec4 color; #endif in vec3 direction; #ifndef BILLBOARD in vec3 initialDirection; #endif #ifdef ANGULARSPEEDGRADIENTS in float angle; #else in vec2 angle; #endif #ifdef ANIMATESHEET in float cellIndex; #ifdef ANIMATESHEETRANDOMSTART in float cellStartOffset; #endif #endif #ifdef NOISE in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; #endif out vec3 outPosition; #ifdef CUSTOMEMITTER out vec3 outInitialPosition; #endif out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; #ifndef COLORGRADIENTS out vec4 outColor; #endif out vec3 outDirection; #ifndef BILLBOARD out vec3 outInitialDirection; #endif #ifdef ANGULARSPEEDGRADIENTS out float outAngle; #else out vec2 outAngle; #endif #ifdef ANIMATESHEET out float outCellIndex; #ifdef ANIMATESHEETRANDOMSTART out float outCellStartOffset; #endif #endif #ifdef NOISE out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; #endif #ifdef SIZEGRADIENTS uniform sampler2D sizeGradientSampler; #endif #ifdef ANGULARSPEEDGRADIENTS uniform sampler2D angularSpeedGradientSampler; #endif #ifdef VELOCITYGRADIENTS uniform sampler2D velocityGradientSampler; #endif #ifdef LIMITVELOCITYGRADIENTS uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; #endif #ifdef DRAGGRADIENTS uniform sampler2D dragGradientSampler; #endif #ifdef NOISE uniform vec3 noiseStrength;uniform sampler2D noiseSampler; #endif #ifdef ANIMATESHEET uniform vec4 cellInfos; #endif vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} void main() {float newAge=age+timeDelta; if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; #ifdef SIZEGRADIENTS outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; #else outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; #endif outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; #ifndef COLORGRADIENTS outColor=color1+(color2-color1)*randoms.b; #endif #ifndef ANGULARSPEEDGRADIENTS outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; #else outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; #endif #ifdef POINTEMITTER vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; #elif defined(BOXEMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; #elif defined(HEMISPHERICEMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; #elif defined(SPHEREEMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); #ifdef DIRECTEDSPHEREEMITTER newDirection=normalize(direction1+(direction2-direction1)*randoms3); #else newDirection=normalize(newPosition+directionRandomizer*randoms3); #endif #elif defined(CYLINDEREMITTER) vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); #ifdef DIRECTEDCYLINDEREMITTER newDirection=direction1+(direction2-direction1)*randoms3; #else angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); #endif #elif defined(CONEEMITTER) vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; #ifdef CONEEMITTERSPAWNPOINT float h=0.0001; #else float h=randoms2.y*height.y;h=1.-h*h; #endif float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); vec3 randoms3=getRandomVec3(seed.z); #ifdef DIRECTEDCONEEMITTER newDirection=direction1+(direction2-direction1)*randoms3; #else if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+directionRandomizer*randoms3); } #endif #elif defined(CUSTOMEMITTER) newPosition=initialPosition;outInitialPosition=initialPosition; #else newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); #endif float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; #ifdef LOCAL outPosition=newPosition; #else outPosition=(emitterWM*vec4(newPosition,1.)).xyz; #endif #ifdef CUSTOMEMITTER outDirection=direction; #ifndef BILLBOARD outInitialDirection=direction; #endif #else #ifdef LOCAL vec3 initial=newDirection; #else vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; #endif outDirection=initial*power; #ifndef BILLBOARD outInitialDirection=initial; #endif #endif #ifdef ANIMATESHEET outCellIndex=cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART outCellStartOffset=randoms.a*outLife; #endif #endif #ifdef NOISE outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; #endif } else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; #ifdef VELOCITYGRADIENTS directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; #endif #ifdef DRAGGRADIENTS directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; #endif #if defined(CUSTOMEMITTER) outPosition=position+(direction-position)*ageGradient; outInitialPosition=initialPosition; #else outPosition=position+direction*directionScale; #endif outLife=life;outSeed=seed; #ifndef COLORGRADIENTS outColor=color; #endif #ifdef SIZEGRADIENTS outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; #else outSize=size; #endif #ifndef BILLBOARD outInitialDirection=initialDirection; #endif #ifdef CUSTOMEMITTER outDirection=direction; #else vec3 updatedDirection=direction+gravity*timeDelta; #ifdef LIMITVELOCITYGRADIENTS float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} #endif outDirection=updatedDirection; #ifdef NOISE float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; #endif #endif #ifdef ANGULARSPEEDGRADIENTS float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; #else outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); #endif #ifdef ANIMATESHEET float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; #else float cellStartOffset=0.; #endif float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} outCellIndex=float(int(cellInfos.x+ratio*dist)); #endif }}`;de.ShadersStore[NMt]=FMt;class JXe{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e;return((e=this._updateEffect)==null?void 0:e.isReady())??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof Ev&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new zi("gpuUpdateParticles",this._updateEffectOptions,this._engine),new qXe(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e, age : f32, size : vec3, life : f32, seed : vec4, direction : vec3, dummy0: f32, #ifdef CUSTOMEMITTER initialPosition : vec3, dummy1: f32, #endif #ifndef COLORGRADIENTS color : vec4, #endif #ifndef BILLBOARD initialDirection : vec3, dummy2: f32, #endif #ifdef NOISE noiseCoordinates1 : vec3, dummy3: f32, noiseCoordinates2 : vec3, dummy4: f32, #endif #ifdef ANGULARSPEEDGRADIENTS angle : f32, #else angle : vec2, #endif #ifdef ANIMATESHEET cellIndex : f32, #ifdef ANIMATESHEETRANDOMSTART cellStartOffset : f32, #endif #endif };struct Particles {particles : array,};struct SimParams {currentCount : f32, timeDelta : f32, stopFactor : f32, randomTextureSize: i32, lifeTime : vec2, emitPower : vec2, #ifndef COLORGRADIENTS color1 : vec4, color2 : vec4, #endif sizeRange : vec2, scaleRange : vec4, angleRange : vec4, gravity : vec3, #ifdef LIMITVELOCITYGRADIENTS limitVelocityDamping : f32, #endif #ifdef ANIMATESHEET cellInfos : vec4, #endif #ifdef NOISE noiseStrength : vec3, #endif #ifndef LOCAL emitterWM : mat4x4, #endif #ifdef BOXEMITTER direction1 : vec3, direction2 : vec3, minEmitBox : vec3, maxEmitBox : vec3, #endif #ifdef CONEEMITTER radius : vec2, coneAngle : f32, height : vec2, #ifdef DIRECTEDCONEEMITTER direction1 : vec3, direction2 : vec3, #else directionRandomizer : f32, #endif #endif #ifdef CYLINDEREMITTER radius : f32, height : f32, radiusRange : f32, #ifdef DIRECTEDCYLINDEREMITTER direction1 : vec3, direction2 : vec3, #else directionRandomizer : f32, #endif #endif #ifdef HEMISPHERICEMITTER radius : f32, radiusRange : f32, directionRandomizer : f32, #endif #ifdef POINTEMITTER direction1 : vec3, direction2 : vec3, #endif #ifdef SPHEREEMITTER radius : f32, radiusRange : f32, #ifdef DIRECTEDSPHEREEMITTER direction1 : vec3, direction2 : vec3, #else directionRandomizer : f32, #endif #endif };@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; #ifdef SIZEGRADIENTS @binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; #endif #ifdef ANGULARSPEEDGRADIENTS @binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; #endif #ifdef VELOCITYGRADIENTS @binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; #endif #ifdef LIMITVELOCITYGRADIENTS @binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; #endif #ifdef DRAGGRADIENTS @binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; #endif #ifdef NOISE @binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; #endif fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; #ifdef SIZEGRADIENTS sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; #else sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; #endif particlesOut.particles[index].size=vec3( sizex, params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); #ifndef COLORGRADIENTS particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; #endif #ifndef ANGULARSPEEDGRADIENTS particlesOut.particles[index].angle=vec2( params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); #else particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; #endif #if defined(POINTEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #elif defined(BOXEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #elif defined(HEMISPHERICEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); #elif defined(SPHEREEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); #ifdef DIRECTEDSPHEREEMITTER newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); #else newDirection=normalize(newPosition+params.directionRandomizer*randoms3); #endif #elif defined(CYLINDEREMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); #ifdef DIRECTEDCYLINDEREMITTER newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #else angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); #endif #elif defined(CONEEMITTER) let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; #ifdef CONEEMITTERSPAWNPOINT let h : f32=0.0001; #else var h : f32=randoms2.y*params.height.y;h=1.-h*h; #endif var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); let randoms3 : vec3=getRandomVec3(seed.z,vertexID); #ifdef DIRECTEDCONEEMITTER newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; #else if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } #endif #elif defined(CUSTOMEMITTER) newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; #else newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); #endif let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; #ifdef LOCAL particlesOut.particles[index].position=newPosition; #else particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; #endif #ifdef CUSTOMEMITTER particlesOut.particles[index].direction=direction; #ifndef BILLBOARD particlesOut.particles[index].initialDirection=direction; #endif #else #ifdef LOCAL let initial : vec3=newDirection; #else let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; #endif particlesOut.particles[index].direction=initial*power; #ifndef BILLBOARD particlesOut.particles[index].initialDirection=initial; #endif #endif #ifdef ANIMATESHEET particlesOut.particles[index].cellIndex=params.cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART particlesOut.particles[index].cellStartOffset=randoms.a*outLife; #endif #endif #ifdef NOISE particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; #endif } else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; #ifdef VELOCITYGRADIENTS directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; #endif #ifdef DRAGGRADIENTS directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); #endif let position : vec3=particlesIn.particles[index].position; #if defined(CUSTOMEMITTER) particlesOut.particles[index].position=position+(direction-position)*ageGradient; particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; #else particlesOut.particles[index].position=position+direction*directionScale; #endif particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; #ifndef COLORGRADIENTS particlesOut.particles[index].color=particlesIn.particles[index].color; #endif #ifdef SIZEGRADIENTS particlesOut.particles[index].size=vec3( textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, particlesIn.particles[index].size.yz); #else particlesOut.particles[index].size=particlesIn.particles[index].size; #endif #ifndef BILLBOARD particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; #endif #ifdef CUSTOMEMITTER particlesOut.particles[index].direction=direction; #else var updatedDirection : vec3=direction+params.gravity*timeDelta; #ifdef LIMITVELOCITYGRADIENTS let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} #endif particlesOut.particles[index].direction=updatedDirection; #ifdef NOISE let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; #endif #endif #ifdef ANGULARSPEEDGRADIENTS let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; #else let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); #endif #ifdef ANIMATESHEET var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; #ifdef ANIMATESHEETRANDOMSTART let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; #else let cellStartOffset : f32=0.; #endif var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); #endif }} `;de.ShadersStoreWGSL[BMt]=kMt;class eYe{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e;return((e=this._updateComputeShader)==null?void 0:e.isReady())??!1}createUpdateBuffer(e){var i;const t={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(t.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(t.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(t.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(t.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(t.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(t.noiseTexture={group:1,binding:11}),this._updateComputeShader=new Hm("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:t,defines:e.split(` `)}),(i=this._simParamsComputeShader)==null||i.dispose(),this._simParamsComputeShader=new zt(this._engine,void 0,void 0,"ComputeShaderParticleSystemUBO"),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new qXe(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new WB(this._engine,e.length*4,11,"ComputeShaderParticleSystemBuffer");return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[e^1]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let t=0;te){i(t[0],t[0],1);return}for(let n=0;n=a.gradient&&e<=o.gradient){const l=(e-a.gradient)/(o.gradient-a.gradient);i(a,o,l);return}}const r=t.length-1;i(t[r],t[r],1)}}class dw{constructor(e){this.particleSystem=e,this.position=D.Zero(),this.direction=D.Zero(),this.color=new Ze(0,0,0,0),this.colorStep=new Ze(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new we(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ze(0,0,0,0),this._currentColor2=new Ze(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=dw._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(this._randomCellOffset===void 0&&(this._randomCellOffset=Math.random()*this.lifeTime),t===0?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let r;this._initialSpriteCellLoop?r=sa(e*t%this.lifeTime/this.lifeTime):r=sa(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+r*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const i=se.Vector3[0];this.direction.normalizeToRef(i),t.setDirection(i,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,se.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(se.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=dw._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new mt(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}dw._Count=0;class dP extends zo{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}get shaderLanguage(){return this._shaderLanguage}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t;return((t=this._customWrappers[e])==null?void 0:t.effect)??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Ro(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Ae),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,n=!1,a=.01){super(e),this._emitterInverseWorldMatrix=he.Identity(),this._inheritedVelocityOffset=new D,this.onDisposeObservable=new Ae,this.onStoppedObservable=new Ae,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ze(0,0,0,0),this._colorDiff=new Ze(0,0,0,0),this._scaledDirection=D.Zero(),this._scaledGravity=D.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._shaderLanguage=0,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=l=>{},this.recycleParticle=l=>{const c=this._particles.pop();c!==l&&c.copyTo(l),this._stockParticles.push(c)},this._createParticle=()=>{let l;return this._stockParticles.length!==0?(l=this._stockParticles.pop(),l._reset()):l=new dw(this),this._prepareParticle(l),l},this._shadersLoaded=!1,this._capacity=t,this._epsilon=a,this._isAnimationSheetEnabled=n,!i||i.getClassName()==="Scene"?(this._scene=i||Rt.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=he.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._initShaderSourceAsync(),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Ro(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new Sv;let o=null;this.updateFunction=l=>{var h;let c=null;this.noiseTexture&&(c=this.noiseTexture.getSize(),(h=this.noiseTexture.getContent())==null||h.then(d=>{o=d}));const u=l===this._particles;for(let d=0;df.lifeTime){const y=f.age-m;p=(f.lifeTime-m)*p/y,f.age=f.lifeTime}const g=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?Kh.GetCurrentGradient(g,this._colorGradients,(y,v,x)=>{y!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),v.getColorToRef(f._currentColor2),f._currentColorGradient=y),Ze.LerpToRef(f._currentColor1,f._currentColor2,x,f.color)}):(f.colorStep.scaleToRef(p,this._scaledColorStep),f.color.addInPlace(this._scaledColorStep),f.color.a<0&&(f.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&Kh.GetCurrentGradient(g,this._angularSpeedGradients,(y,v,x)=>{y!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=v.getFactor(),f._currentAngularSpeedGradient=y),f.angularSpeed=Md(f._currentAngularSpeed1,f._currentAngularSpeed2,x)}),f.angle+=f.angularSpeed*p;let _=p;if(this._velocityGradients&&this._velocityGradients.length>0&&Kh.GetCurrentGradient(g,this._velocityGradients,(y,v,x)=>{y!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=v.getFactor(),f._currentVelocityGradient=y),_*=Md(f._currentVelocity1,f._currentVelocity2,x)}),f.direction.scaleToRef(_,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&Kh.GetCurrentGradient(g,this._limitVelocityGradients,(y,v,x)=>{y!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=v.getFactor(),f._currentLimitVelocityGradient=y);const A=Md(f._currentLimitVelocity1,f._currentLimitVelocity2,x);f.direction.length()>A&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&Kh.GetCurrentGradient(g,this._dragGradients,(y,v,x)=>{y!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=v.getFactor(),f._currentDragGradient=y);const A=Md(f._currentDrag1,f._currentDrag2,x);this._scaledDirection.scaleInPlace(1-A)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),D.TransformCoordinatesToRef(f._localPosition,this._emitterWorldMatrix,f.position)):f.position.addInPlace(this._scaledDirection),o&&c&&f._randomNoiseCoordinates1){const y=this._fetchR(f._randomNoiseCoordinates1.x,f._randomNoiseCoordinates1.y,c.width,c.height,o),v=this._fetchR(f._randomNoiseCoordinates1.z,f._randomNoiseCoordinates2.x,c.width,c.height,o),x=this._fetchR(f._randomNoiseCoordinates2.y,f._randomNoiseCoordinates2.z,c.width,c.height,o),A=se.Vector3[0],b=se.Vector3[1];A.copyFromFloats((2*y-1)*this.noiseStrength.x,(2*v-1)*this.noiseStrength.y,(2*x-1)*this.noiseStrength.z),A.scaleToRef(p,b),f.direction.addInPlace(b)}if(this.gravity.scaleToRef(p,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&Kh.GetCurrentGradient(g,this._sizeGradients,(y,v,x)=>{y!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=v.getFactor(),f._currentSizeGradient=y),f.size=Md(f._currentSize1,f._currentSize2,x)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&Kh.GetCurrentGradient(g,this._colorRemapGradients,(y,v,x)=>{const A=Md(y.factor1,v.factor1,x),b=Md(y.factor2,v.factor2,x);f.remapData.x=A,f.remapData.y=b-A}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&Kh.GetCurrentGradient(g,this._alphaRemapGradients,(y,v,x)=>{const A=Md(y.factor1,v.factor1,x),b=Md(y.factor2,v.factor2,x);f.remapData.z=A,f.remapData.w=b-A})),this._isAnimationSheetEnabled&&f.updateCellIndex(),f._inheritParticleInfoToSubEmitters(),f.age>=f.lifeTime){this._emitFromParticle(f),f._attachedSubEmitters&&(f._attachedSubEmitters.forEach(y=>{y.particleSystem.disposeOnStop=!0,y.particleSystem.stop()}),f._attachedSubEmitters=null),this.recycleParticle(f),u&&d--;continue}}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,r){const n=new B_e(t,i,r);e.push(n),e.sort((a,o)=>a.gradiento.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(this._rawTextureWidth*4),t=ts.Color3[0];for(let i=0;i{Re.LerpToRef(n.color,a.color,o,t),e[i*4]=t.r*255,e[i*4+1]=t.g*255,e[i*4+2]=t.b*255,e[i*4+3]=255})}this._rampGradientsTexture=yn.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new tYe(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const r=new F_e(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((n,a)=>n.gradienta.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t==null||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,n){e=Math.abs(e)*.5+.5,t=Math.abs(t)*.5+.5;const a=e*i%i|0,o=t*r%r|0,l=(a+o*i)*4;return n[l]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9)&&(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Mo(e,this._vertexData,!0,t);let i=0;const r=this._vertexBuffer.createVertexBuffer($.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[$.PositionKind]=r,i+=3;const n=this._vertexBuffer.createVertexBuffer($.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[$.ColorKind]=n,i+=4;const a=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const c=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=c,i+=1}if(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9){const c=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=c,i+=3}if(this._useRampGradients){const c=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=c,i+=4}let l;if(this._useInstancing){const c=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Mo(e,c,!1,2),l=this._spriteBuffer.createVertexBuffer("offset",0,2)}else l=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=l,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}const e=[],t=[];let i=0;for(let r=0;r{this.start(0)},e);return}if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){((t=this.emitter)==null?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);const i=this.noiseTexture;if(i&&i.onGeneratedObservable)i.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let r=0;r0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let n=e*this._vertexBufferSize;if(this._vertexData[n++]=t.position.x+this.worldOffset.x,this._vertexData[n++]=t.position.y+this.worldOffset.y,this._vertexData[n++]=t.position.z+this.worldOffset.z,this._vertexData[n++]=t.color.r,this._vertexData[n++]=t.color.g,this._vertexData[n++]=t.color.b,this._vertexData[n++]=t.color.a,this._vertexData[n++]=t.angle,this._vertexData[n++]=t.scale.x*t.size,this._vertexData[n++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[n++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===8||this.billboardMode===9)&&(this._vertexData[n++]=t.direction.x,this._vertexData[n++]=t.direction.y,this._vertexData[n++]=t.direction.z);else if(t._initialDirection){let a=t._initialDirection;this.isLocal&&(D.TransformNormalToRef(a,this._emitterWorldMatrix,se.Vector3[0]),a=se.Vector3[0]),a.x===0&&a.z===0&&(a.x=.001),this._vertexData[n++]=a.x,this._vertexData[n++]=a.y,this._vertexData[n++]=a.z}else{let a=t.direction;this.isLocal&&(D.TransformNormalToRef(a,this._emitterWorldMatrix,se.Vector3[0]),a=se.Vector3[0]),a.x===0&&a.z===0&&(a.x=.001),this._vertexData[n++]=a.x,this._vertexData[n++]=a.y,this._vertexData[n++]=a.z}this._useRampGradients&&t.remapData&&(this._vertexData[n++]=t.remapData.x,this._vertexData[n++]=t.remapData.y,this._vertexData[n++]=t.remapData.z,this._vertexData[n++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),r===0?r=this._epsilon:r===1&&(r=1-this._epsilon)),this._vertexData[n++]=i,this._vertexData[n++]=r)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{const i=this.emitter;this._emitterWorldMatrix=he.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const n=sa(this._actualFrame/this.targetStopDuration);Kh.GetCurrentGradient(n,this._lifeTimeGradients,(a,o)=>{const l=a,c=o,u=l.getFactor(),h=c.getFactor(),d=(n-l.gradient)/(c.gradient-l.gradient);t.lifeTime=Md(u,h,d)})}else t.lifeTime=Es(this.minLifeTime,this.maxLifeTime);const r=Es(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),D.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),r===0?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(r),!this._sizeGradients||this._sizeGradients.length===0?t.size=Es(this.minSize,this.maxSize):(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1),t.scale.copyFromFloats(Es(this.minScaleX,this.maxScaleX),Es(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const n=this._actualFrame/this.targetStopDuration;Kh.GetCurrentGradient(n,this._startSizeGradients,(a,o,l)=>{a!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=o.getFactor(),this._currentStartSizeGradient=a);const c=Md(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(c)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=Es(this.minAngularSpeed,this.maxAngularSpeed):(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1),t.angle=Es(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),!this._colorGradients||this._colorGradients.length===0){const n=Es(0,1);Ze.LerpToRef(this.color1,this.color2,n,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}else t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new mt(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new D(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new D(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const r=[$.PositionKind,$.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["invView","view","projection","textureMask","translationPivot","eyePosition"];return fo(r),e&&r.push("particlesInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t,i=!0){if(this._scene&&(t3(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==0&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===zo.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===9&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL");break}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...dP._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==8&&this.billboardMode!==9,this._useRampGradients)),e.push(...dP._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(d9e(e,this._imageProcessingConfigurationDefines),f9e(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);const r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let n=this._drawWrappers[r];n||(n=this._drawWrappers[r]=[]);let a=n[e];a||(a=new Ro(this._engine),a.drawContext&&(a.drawContext.useInstancing=this._useInstancing),n[e]=a);const o=i.join(` `);if(a.defines!==o){const l=[],c=[],u=[];this.fillUniformsAttributesAndSamplerNames(c,l,u),a.setEffect(this._engine.createEffect("particles",l,c,u,o,void 0,void 0,void 0,void 0,this._shaderLanguage),o)}return a}animate(e=!1){var i;if(!this._started)return;if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:((i=this._scene)==null?void 0:i.getAnimationRatio())||1);let t;if(this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let r=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const n=this._actualFrame/this.targetStopDuration;Kh.GetCurrentGradient(n,this._emitRateGradients,(a,o,l)=>{a!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=o.getFactor(),this._currentEmitRateGradient=a),r=Md(this._currentEmitRate1,this._currentEmitRate2,l)})}t=r*this._scaledUpdateSpeed>>0,this._newPartsExcess+=r*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let r=0;for(let n=0;nPromise.resolve().then(()=>TYe),void 0),Ue(()=>Promise.resolve().then(()=>$Mt),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>yYe),void 0),Ue(()=>Promise.resolve().then(()=>QMt),void 0)]),this._shadersLoaded=!0}isReady(){if(!this._shadersLoaded||!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==zo.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(zo.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(zo.BLENDMODE_ADD).effect.isReady())return!1;return!0}_render(e){var o,l,c,u,h,d;const t=this._getWrapper(e),i=t.effect,r=this._engine;r.enableEffect(t);const n=this.defaultViewMatrix??this._scene.getViewMatrix();if(i.setTexture("diffuseSampler",this.particleTexture),i.setMatrix("view",n),i.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){const f=this.particleTexture.getBaseSize();i.setFloat3("particlesInfos",this.spriteCellWidth/f.width,this.spriteCellHeight/f.height,this.spriteCellWidth/f.width)}if(i.setVector2("translationPivot",this.translationPivot),i.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){const f=this._scene.activeCamera;i.setVector3("eyePosition",f.globalPosition)}this._rampGradientsTexture&&((!this._rampGradients||!this._rampGradients.length)&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),i.setTexture("rampSampler",this._rampGradientsTexture));const a=i.defines;switch(this._scene&&(Xa(i,this,this._scene),this.applyFog&&ml(this._scene,void 0,i)),a.indexOf("#define BILLBOARDMODE_ALL")>=0&&(n.invertToRef(se.Matrix[0]),i.setMatrix("invView",se.Matrix[0])),this._vertexArrayObject!==void 0?(o=this._scene)!=null&&o.forceWireframe?r.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?r.bindBuffers(this._vertexBuffers,(u=this._scene)!=null&&u.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):r.bindBuffers(this._vertexBuffers,(c=this._scene)!=null&&c.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&uo(a,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case zo.BLENDMODE_ADD:r.setAlphaMode(1);break;case zo.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case zo.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case zo.BLENDMODE_MULTIPLY:r.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?(h=this._scene)!=null&&h.forceWireframe?r.drawElementsType(6,0,10,this._particles.length):r.drawArraysType(7,0,4,this._particles.length):(d=this._scene)!=null&&d.forceWireframe?r.drawElementsType(1,0,this._particles.length*10):r.drawElementsType(0,0,this._particles.length*6),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return this.blendMode===zo.BLENDMODE_MULTIPLYADD?t=this._render(zo.BLENDMODE_MULTIPLY)+this._render(zo.BLENDMODE_ADD):t=this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const r=this._scene.particleSystems.indexOf(this);r>-1&&this._scene.particleSystems.splice(r,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}dP.ForceGLSL=!1;var Ade;(function(s){s[s.ATTACHED=0]="ATTACHED",s[s.END=1]="END"})(Ade||(Ade={}));class Tv{constructor(e){if(this.particleSystem=e,this.type=1,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Xn("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new D;else if(e instanceof D)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=Xn("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new Tv(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw vi("ParseParticle")}static Parse(e,t,i){const r=e.particleSystem,n=new Tv(Tv._ParseParticleSystem(r,t,i,!0));return n.type=e.type,n.inheritDirection=e.inheritDirection,n.inheritedVelocityAmount=e.inheritedVelocityAmount,n.particleSystem._isSubEmitter=!0,n}dispose(){this.particleSystem.dispose()}}function iYe(s,e){const t=new iV;return t.direction1=s,t.direction2=e,t}function rYe(s=1,e=1){return new tV(s,e)}function sYe(s=1,e=1){return new cD(s,e)}function nYe(s=1,e=new D(0,1,0),t=new D(0,1,0)){return new rV(s,e,t)}function aYe(s=1,e=1,t=1,i=0){return new lD(s,e,t,i)}function oYe(s=1,e=1,t=1,i=new D(0,1,0),r=new D(0,1,0)){return new eV(s,e,t,i,r)}function lYe(s=1,e=Math.PI/4){return new oD(s,e)}function cYe(s=1,e=Math.PI/4,t=new D(0,1,0),i=new D(0,1,0)){return new Jz(s,e,t,i)}class bs extends dP{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||this._subEmitters.length===0)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(i=>{if(i.type===1){const r=i.clone();e._inheritParticleInfoToSubEmitter(r),r.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(r.particleSystem),r.particleSystem.start()}})}}createPointEmitter(e,t){const i=iYe(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=rYe(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=sYe(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new D(0,1,0),i=new D(0,1,0)){const r=nYe(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){const n=aYe(e,t,i,r);return this.particleEmitterType=n,n}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new D(0,1,0),n=new D(0,1,0)){const a=oYe(e,t,i,r,n);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=lYe(e,t);return this.particleEmitterType=i,i}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new D(0,1,0),r=new D(0,1,0)){const n=cYe(e,t,i,r);return this.particleEmitterType=n,n}createBoxEmitter(e,t,i,r){const n=new Sv;return this.particleEmitterType=n,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,n}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof bs?this._subEmitters.push([new Tv(e)]):e instanceof Tv?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);e!==-1&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(i=>{if(i.type===0){const r=i.clone();e._attachedSubEmitters.push(r),r.particleSystem.start()}})}}_onDispose(e=!1,t=!1){var i;if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&((i=this.particles)==null||i.forEach(r=>{if(r._attachedSubEmitters)for(let n=r._attachedSubEmitters.length-1;n>=0;n-=1)r._attachedSubEmitters[n].dispose()})),t&&this.activeSubSystems)for(let r=this.activeSubSystems.length-1;r>=0;r-=1)this.activeSubSystems[r].dispose();if(this._subEmitters&&this._subEmitters.length){for(let r=0;r0?l.shaderOptions.defines.join(` `):"";o=c.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,d)}const h=new bs(a,n||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters){h.subEmitters=[];for(const d of e.subEmitters){const f=[];for(const p of d)f.push(Tv.Parse(p,t,i));h.subEmitters.push(f)}}return bs._Parse(e,h,t,i),e.textureMask&&(h.textureMask=Ze.FromArray(e.textureMask)),e.worldOffset&&(h.worldOffset=D.FromArray(e.worldOffset)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),!r&&!h.preventAutoStart&&h.start(),h}serialize(e=!1){const t={};if(bs._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const r=[];for(const n of i)r.push(n.serialize(e));t.subEmitters.push(r)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const g=t.emitter;e.emitterId=g.id}else{const g=t.emitter;e.emitter=g.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,qe.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const r=t.getColorGradients();if(r){e.colorGradients=[];for(const g of r){const _={gradient:g.gradient,color1:g.color1.asArray()};g.color2?_.color2=g.color2.asArray():_.color2=g.color1.asArray(),e.colorGradients.push(_)}}const n=t.getRampGradients();if(n){e.rampGradients=[];for(const g of n){const _={gradient:g.gradient,color:g.color.asArray()};e.rampGradients.push(_)}e.useRampGradients=t.useRampGradients}const a=t.getColorRemapGradients();if(a){e.colorRemapGradients=[];for(const g of a){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.colorRemapGradients.push(_)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const g of o){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.alphaRemapGradients.push(_)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const g of l){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.sizeGradients.push(_)}}const c=t.getAngularSpeedGradients();if(c){e.angularSpeedGradients=[];for(const g of c){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.angularSpeedGradients.push(_)}}const u=t.getVelocityGradients();if(u){e.velocityGradients=[];for(const g of u){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.velocityGradients.push(_)}}const h=t.getDragGradients();if(h){e.dragGradients=[];for(const g of h){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.dragGradients.push(_)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const g of d){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.emitRateGradients.push(_)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const g of f){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.startSizeGradients.push(_)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const g of p){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.lifeTimeGradients.push(_)}}const m=t.getLimitVelocityGradients();if(m){e.limitVelocityGradients=[];for(const g of m){const _={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?_.factor2=g.factor2:_.factor2=g.factor1,e.limitVelocityGradients.push(_)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const r={...this._customWrappers};let n=null;const a=this._engine;if(a.createEffectForParticles&&this.customShader!=null){n=this.customShader;const c=n.shaderOptions.defines.length>0?n.shaderOptions.defines.join(` `):"",u=a.createEffectForParticles(n.shaderPath.fragmentElement,n.shaderOptions.uniforms,n.shaderOptions.samplers,c);r[0]?r[0].effect=u:this.setCustomEffect(u,0)}const o=this.serialize(i),l=bs.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=n,l._customWrappers=r,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,this.preventAutoStart||l.start(),l}}bs.BILLBOARDMODE_Y=2;bs.BILLBOARDMODE_ALL=7;bs.BILLBOARDMODE_STRETCHED=8;bs.BILLBOARDMODE_STRETCHED_LOCAL=9;Tv._ParseParticleSystem=bs.Parse;const UMt="clipPlaneFragmentDeclaration2",zMt=`#ifdef CLIPPLANE in float fClipDistance; #endif #ifdef CLIPPLANE2 in float fClipDistance2; #endif #ifdef CLIPPLANE3 in float fClipDistance3; #endif #ifdef CLIPPLANE4 in float fClipDistance4; #endif #ifdef CLIPPLANE5 in float fClipDistance5; #endif #ifdef CLIPPLANE6 in float fClipDistance6; #endif `;de.IncludesShadersStore[UMt]=zMt;const VMt="gpuRenderParticlesPixelShader",GMt=`precision highp float; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; #include #include #include #include #include #include void main() { #include vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; #ifdef BLENDMULTIPLYMODE float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); #endif #include #include(color,gl_FragColor) #ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); #else #ifdef IMAGEPROCESSING gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); #endif #endif } `;de.ShadersStore[VMt]=GMt;const WMt="clipPlaneVertexDeclaration2",KMt=`#ifdef CLIPPLANE uniform vec4 vClipPlane;out float fClipDistance; #endif #ifdef CLIPPLANE2 uniform vec4 vClipPlane2;out float fClipDistance2; #endif #ifdef CLIPPLANE3 uniform vec4 vClipPlane3;out float fClipDistance3; #endif #ifdef CLIPPLANE4 uniform vec4 vClipPlane4;out float fClipDistance4; #endif #ifdef CLIPPLANE5 uniform vec4 vClipPlane5;out float fClipDistance5; #endif #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;out float fClipDistance6; #endif `;de.IncludesShadersStore[WMt]=KMt;const HMt="gpuRenderParticlesVertexShader",jMt=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; #ifdef LOCAL uniform mat4 emitterWM; #endif attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; #ifndef BILLBOARD attribute vec3 initialDirection; #endif #ifdef BILLBOARDSTRETCHED attribute vec3 direction; #endif attribute float angle; #ifdef ANIMATESHEET attribute float cellIndex; #endif attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform mat4 invView; #endif #include #include #include #ifdef COLORGRADIENTS uniform sampler2D colorGradientSampler; #else uniform vec4 colorDead;attribute vec4 color; #endif #ifdef ANIMATESHEET uniform vec3 sheetInfos; #endif #ifdef BILLBOARD uniform vec3 eyePosition; #endif vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; #ifdef LOCAL return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; #else return (position+worldOffset)+alignedCorner; #endif } #ifdef BILLBOARDSTRETCHED vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; #ifdef LOCAL return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; #else return (position+worldOffset)+alignedCorner; #endif } #endif void main() { #ifdef ANIMATESHEET float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; #else vUV=uv; #endif float ratio=min(1.0,age/life); #ifdef COLORGRADIENTS vColor=texture2D(colorGradientSampler,vec2(ratio,0)); #else vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); #endif vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; #ifdef BILLBOARD vec4 rotatedCorner;rotatedCorner.w=0.; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); #else rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; #ifdef LOCAL vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; #else vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; #endif vPositionW=(invView*viewPosition).xyz; #endif #else vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); #endif gl_Position=projection*viewPosition; #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include #include }`;de.ShadersStore[HMt]=jMt;class Hd extends zo{static get IsSupported(){if(!Rt.LastCreatedEngine)return!1;const e=Rt.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=iYe(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=rYe(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=sYe(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new D(0,1,0),i=new D(0,1,0)){const r=nYe(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){const n=aYe(e,t,i,r);return this.particleEmitterType=n,n}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new D(0,1,0),n=new D(0,1,0)){const a=oYe(e,t,i,r,n);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=lYe(e,t);return this.particleEmitterType=i,i}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new D(0,1,0),r=new D(0,1,0)){const n=cYe(e,t,i,r);return this.particleEmitterType=n,n}createBoxEmitter(e,t,i,r){const n=new Sv;return this.particleEmitterType=n,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,n}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==bs.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(bs.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(bs.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t;return((t=this._customWrappers[e])==null?void 0:t.effect)??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Ro(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Ae),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[this._targetIndex^1]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new F_e(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((t,i)=>t.gradienti.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(const t in this._drawWrappers)(e=this._drawWrappers[t].drawContext)==null||e.reset()}_addFactorGradient(e,t,i){const r=new B_e(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort((n,a)=>n.gradienta.gradient?1:0);const r=this;r[t]&&(r[t].dispose(),r[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,n=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new Ae,this.onStoppedObservable=new Ae,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||Rt.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=he.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!Xn("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Xn("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!Xn("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Xn("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Ro(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new Ro(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),t=t??{},t.randomTextureSize||delete t.randomTextureSize;const a={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(a.capacity=o),this._capacity=a.capacity,this._maxActiveParticleCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=n,this.particleEmitterType=new Sv;const l=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize);let c=[];for(let u=0;u0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),l=this._platform.createParticleBuffer(i),c=this._platform.createParticleBuffer(i);this._buffer0=new Mo(t,l,!1,this._attributesStrideSize),this._buffer1=new Mo(t,c,!1,this._attributesStrideSize),this._spriteBuffer=new Mo(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+=` #define BILLBOARD`),this._colorGradientsTexture&&(e+=` #define COLORGRADIENTS`),this._sizeGradientsTexture&&(e+=` #define SIZEGRADIENTS`),this._angularSpeedGradientsTexture&&(e+=` #define ANGULARSPEEDGRADIENTS`),this._velocityGradientsTexture&&(e+=` #define VELOCITYGRADIENTS`),this._limitVelocityGradientsTexture&&(e+=` #define LIMITVELOCITYGRADIENTS`),this._dragGradientsTexture&&(e+=` #define DRAGGRADIENTS`),this.isAnimationSheetEnabled&&(e+=` #define ANIMATESHEET`,this.spriteRandomStartCell&&(e+=` #define ANIMATESHEETRANDOMSTART`)),this.noiseTexture&&(e+=` #define NOISE`),this.isLocal&&(e+=` #define LOCAL`),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e?this._platform.isUpdateBufferReady():(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||(r=new Ro(this._engine),r.drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);const n=i.join(` `);if(r.defines!==n){const a=[],o=[],l=[];this.fillUniformsAttributesAndSamplerNames(o,a,l),r.setEffect(this._engine.createEffect("gpuRenderParticles",a,o,l,n),n)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){const n=[$.PositionKind,"age","life","size","angle"];return e||n.push($.ColorKind),t&&n.push("cellIndex"),i||n.push("initialDirection"),r&&n.push("direction"),n.push("offset",$.UVKind),n}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return fo(r),e&&r.push("sheetInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t=0,i=!0){if(this._scene&&(t3(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==gt.FOGMODE_NONE&&e.push("#define FOG")),t===bs.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case bs.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case bs.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case bs.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Hd._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===bs.BILLBOARDMODE_STRETCHED)),e.push(...Hd._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(lr.PrepareUniforms(e,this._imageProcessingConfigurationDefines),lr.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((t=this._scene)==null?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const r=new Float32Array(this._rawTextureWidth);for(let n=0;n{r[n]=At.Lerp(o.factor1,l.factor1,c)})}this[t]=yn.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(this._rawTextureWidth*4),t=ts.Color4[0];for(let i=0;i{Ze.LerpToRef(n.color1,a.color1,o,t),e[i*4]=t.r*255,e[i*4+1]=t.g*255,e[i*4+2]=t.b*255,e[i*4+3]=t.a*255})}this._colorGradientsTexture=yn.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var o,l,c,u;const i=this._getWrapper(e),r=i.effect;this._engine.enableEffect(i);const n=((o=this._scene)==null?void 0:o.getViewMatrix())||he.IdentityReadOnly;if(r.setMatrix("view",n),r.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const h=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/h.width,this.spriteCellHeight/h.height,h.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const h=this._scene.activeCamera;r.setVector3("eyePosition",h.globalPosition)}const a=r.defines;if(this._scene&&(Xa(r,this,this._scene),this.applyFog&&ml(this._scene,void 0,r)),a.indexOf("#define BILLBOARDMODE_ALL")>=0){const h=n.clone();h.invert(),r.setMatrix("invView",h)}switch(this.useLogarithmicDepth&&this._scene&&uo(a,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case bs.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case bs.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case bs.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case bs.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,r,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),(c=this._scene)!=null&&c.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(u=this._scene)!=null&&u.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const i=this.emitter;e=se.Matrix[0],he.TranslationToRef(i.x,i.y,i.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,this._targetIndex===2&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let a=0;a1){const a=this._accumulatedCount|0;this._accumulatedCount-=a,this._currentActiveCount+=a}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const a=this.emitter;i=se.Matrix[0],he.TranslationToRef(a.x,a.y,a.z,i)}const r=this._engine;this.updateInAnimate||this._update(i);let n=0;return!e&&!t&&(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),this.blendMode===bs.BLENDMODE_MULTIPLYADD?n=this._render(bs.BLENDMODE_MULTIPLY,i)+this._render(bs.BLENDMODE_ADD,i):n=this._render(this.blendMode,i),this._engine.setAlphaMode(0)),n}rebuild(){const e=()=>{!this._recreateUpdateEffect()||!this._platform.isUpdateBufferReady()?setTimeout(e,10):(this._initialize(!0),this._rebuildingAfterContextLost=!1)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const t in this._drawWrappers)this._drawWrappers[t].dispose();if(this._drawWrappers={},this._scene){const t=this._scene.particleSystems.indexOf(this);t>-1&&this._scene.particleSystems.splice(t,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let t=0;t0?n.shaderOptions.defines.join(` `):"";r[0]=a.createEffectForParticles(n.shaderPath.fragmentElement,n.shaderOptions.uniforms,n.shaderOptions.samplers,c,void 0,void 0,void 0,this)}const o=this.serialize(i),l=Hd.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=n,l._customWrappers=r,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,l}serialize(e=!1){const t={};return bs._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,n){const a=e.name;let o,l;t instanceof Ge?o=t:(l=t,o=l.getEngine());const c=new Hd(a,{capacity:n||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(c._rootUrl=i,e.customShader&&o.createEffectForParticles){const u=e.customShader,h=u.shaderOptions.defines.length>0?u.shaderOptions.defines.join(` `):"",d=o.createEffectForParticles(u.shaderPath.fragmentElement,u.shaderOptions.uniforms,u.shaderOptions.samplers,h,void 0,void 0,void 0,c);c.setCustomEffect(d,0),c.customShader=u}return e.id&&(c.id=e.id),e.activeParticleCount&&(c.activeParticleCount=e.activeParticleCount),bs._Parse(e,c,t,i),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),!r&&!c.preventAutoStart&&c.start(),c}}class Vv{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const r=kc("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;const n=new et("emitterSphereMaterial",i);n.emissiveColor=e.color,r.material=n;for(const a of this.systems)a.emitter=r;this._emitterNode=r}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={};t.systems=[];for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){const n=new Vv,a=this.BaseAssetsUrl+"/textures/";t=t||Rt.LastCreatedScene;for(const o of e.systems)n.systems.push(i?Hd.Parse(o,t,a,!0,r):bs.Parse(o,t,a,!0,r));if(e.emitter){const o=e.emitter.options;switch(e.emitter.kind){case"Sphere":n.setEmitterAsSphere({diameter:o.diameter,segments:o.segments,color:Re.FromArray(o.color)},e.emitter.renderingGroupId,t);break}}return n}}Vv.BaseAssetsUrl="https://assets.babylonjs.com/particles";class c6{static CreateDefault(e,t=500,i,r=!1){let n;return r?n=new Hd("default system",{capacity:t},i):n=new bs("default system",t,i),n.emitter=e,n.particleTexture=new xe("https://assets.babylonjs.com/textures/flare.png",n.getScene()),n.createConeEmitter(.1,Math.PI/4),n.color1=new Ze(1,1,1,1),n.color2=new Ze(1,1,1,1),n.colorDead=new Ze(1,1,1,0),n.minSize=.1,n.maxSize=.1,n.minEmitPower=2,n.maxEmitPower=2,n.updateSpeed=1/60,n.emitRate=30,n}static CreateAsync(e,t,i=!1,r){t||(t=Rt.LastCreatedScene);const n={};return t.addPendingData(n),new Promise((a,o)=>{if(i&&!Hd.IsSupported)return t.removePendingData(n),o("Particle system with GPU is not supported.");Me.LoadFile(`${c6.BaseAssetsUrl}/systems/${e}.json`,l=>{t.removePendingData(n);const c=JSON.parse(l.toString());return a(Vv.Parse(c,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(n),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){const t=new Vv;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,n="",a){return new Promise((o,l)=>{const c=new On;c.addEventListener("readystatechange",()=>{if(c.readyState==4)if(c.status==200){const u=JSON.parse(c.responseText);let h;r?h=Hd.Parse(u,i,n,!1,a):h=bs.Parse(u,i,n,!1,a),e&&(h.name=e),o(h)}else l("Unable to load the particle system")}),c.open("GET",t),c.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",n){if(e==="_BLANK"){const a=this.CreateDefault(null);return a.start(),Promise.resolve(a)}return new Promise((a,o)=>{const l=new On;l.addEventListener("readystatechange",()=>{if(l.readyState==4)if(l.status==200){const c=JSON.parse(JSON.parse(l.responseText).jsonPayload),u=JSON.parse(c.particleSystem);let h;i?h=Hd.Parse(u,t,r,!1,n):h=bs.Parse(u,t,r,!1,n),h.snippetId=e,a(h)}else o("Unable to load the snippet "+e)}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}}c6.BaseAssetsUrl=Vv.BaseAssetsUrl;c6.SnippetUrl="https://snippet.babylonjs.com";c6.CreateFromSnippetAsync=c6.ParseFromSnippetAsync;Oa.AddParser(ot.NAME_PARTICLESYSTEM,(s,e,t,i)=>{const r=Oa.GetIndividualParser(ot.NAME_PARTICLESYSTEM);if(r&&s.particleSystems!==void 0&&s.particleSystems!==null)for(let n=0,a=s.particleSystems.length;ns.activeParticleCount?Hd.Parse(s,e,t):bs.Parse(s,e,t));Ge.prototype.createEffectForParticles=function(s,e=[],t=[],i="",r,n,a,o,l=0){let c=[],u=[];const h=[];return o?o.fillUniformsAttributesAndSamplerNames(u,c,h):(c=bs._GetAttributeNamesOrOptions(),u=bs._GetEffectCreationOptions()),i.indexOf(" BILLBOARD")===-1&&(i+=` #define BILLBOARD `),o!=null&&o.isAnimationSheetEnabled&&i.indexOf(" ANIMATESHEET")===-1&&(i+=` #define ANIMATESHEET `),t.indexOf("diffuseSampler")===-1&&t.push("diffuseSampler"),this.createEffect({vertex:(o==null?void 0:o.vertexShaderName)??"particles",fragmentElement:s},c,u.concat(e),h.concat(t),i,r,n,a,void 0,l,async()=>{l===0?await Ue(()=>Promise.resolve().then(()=>yYe),void 0):await Ue(()=>Promise.resolve().then(()=>TYe),void 0)})};Ee.prototype.getEmittedParticleSystems=function(){const s=[];for(let e=0;en.sqDistance-r.sqDistance,this._materialSortFunction=(r,n)=>r.materialIndex-n.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||Rt.LastCreatedScene,this._camera=t.activeCamera,this._pickable=i?i.isPickable:!1,this._depthSort=i?i.enableDepthSort:!1,this._multimaterialEnabled=i?i.enableMultiMaterial:!1,this._useModelMaterial=i?i.useModelMaterial:!1,this._multimaterialEnabled=this._useModelMaterial?!0:this._multimaterialEnabled,this._expandable=i?i.expandable:!1,this._particlesIntersect=i?i.particleIntersection:!1,this._bSphereOnly=i?i.boundingSphereOnly:!1,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=i!=null&&i.computeBoundingBox?i.computeBoundingBox:!1,this._autoFixFaceOrientation=i!=null&&i.autoFixFaceOrientation?i.autoFixFaceOrientation:!1,i&&i.updatable!==void 0?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new Zd(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new hYe}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(this.nbParticles===0&&!this.mesh){const t=iD("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const t=new Ee(this.name,this._scene);this.mesh=t}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&at.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new at;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,$.PositionKind),e.set(this._normals32,$.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,$.UVKind),this._colors32.length>0&&e.set(this._colors32,$.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let t=0;for(let i=0;if?f:r,i=Math.round(f/r),n=0):i=i>f?f:i;const p=[],m=[],g=[],_=[],y=[],v=D.Zero(),x=i;for(;df-i&&(i=f-d),p.length=0,m.length=0,g.length=0,_.length=0,y.length=0;let A=0;for(let K=d*3;K<(d+i)*3;K++){g.push(A);const U=o[K],W=U*3;if(p.push(a[W],a[W+1],a[W+2]),m.push(u[W],u[W+1],u[W+2]),l){const Z=U*2;_.push(l[Z],l[Z+1])}if(c){const Z=U*4;y.push(c[Z],c[Z+1],c[Z+2],c[Z+3])}A++}let b=this.nbParticles;const C=this._posToShape(p),T=this._uvsToShapeUV(_),w=g.slice(),P=y.slice(),M=m.slice();v.copyFromFloats(0,0,0);let R;for(R=0;R65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const V=A.materialIndex!==null?A.materialIndex:0;this.depthSortedParticles.push(new uYe(f,t,n.length,V))}return A}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const r=this.particles,n=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const j=this.mesh.getBoundingInfo();j&&(v.copyFrom(j.minimum),x.copyFrom(j.maximum))}M=this.particles[e]._pos;const H=M/3|0;I=H*4,k=H*2;for(let j=e;j<=t;j++){const z=this.particles[j];this.updateParticle(z);const K=z._model._shape,U=z._model._shapeUV,W=z._rotationMatrix,Z=z.position,q=z.rotation,ie=z.scaling,ae=z._globalPosition;if(p){const ue=this.depthSortedParticles[j];ue.idx=z.idx,ue.ind=z._ind,ue.indicesLength=z._model._indicesLength,ue.sqDistance=D.DistanceSquared(z.position,A)}if(!z.alive||z._stillInvisible&&!z.isVisible&&!this._recomputeInvisibles){V=K.length,M+=V*3,I+=V*4,k+=V*2;continue}if(z.isVisible){z._stillInvisible=!1;const ue=m[12];if(z.pivot.multiplyToRef(ie,ue),this.billboard&&(q.x=0,q.y=0),(this._computeParticleRotation||this.billboard)&&z.getRotationMatrix(r),z.parentId!==null){const B=this.getParticleById(z.parentId);if(B){const Y=B._rotationMatrix,te=B._globalPosition,oe=Z.x*Y[1]+Z.y*Y[4]+Z.z*Y[7],ne=Z.x*Y[0]+Z.y*Y[3]+Z.z*Y[6],pe=Z.x*Y[2]+Z.y*Y[5]+Z.z*Y[8];if(ae.x=te.x+ne,ae.y=te.y+oe,ae.z=te.z+pe,this._computeParticleRotation||this.billboard){const ye=r.m;W[0]=ye[0]*Y[0]+ye[1]*Y[3]+ye[2]*Y[6],W[1]=ye[0]*Y[1]+ye[1]*Y[4]+ye[2]*Y[7],W[2]=ye[0]*Y[2]+ye[1]*Y[5]+ye[2]*Y[8],W[3]=ye[4]*Y[0]+ye[5]*Y[3]+ye[6]*Y[6],W[4]=ye[4]*Y[1]+ye[5]*Y[4]+ye[6]*Y[7],W[5]=ye[4]*Y[2]+ye[5]*Y[5]+ye[6]*Y[8],W[6]=ye[8]*Y[0]+ye[9]*Y[3]+ye[10]*Y[6],W[7]=ye[8]*Y[1]+ye[9]*Y[4]+ye[10]*Y[7],W[8]=ye[8]*Y[2]+ye[9]*Y[5]+ye[10]*Y[8]}}else z.parentId=null}else if(ae.x=Z.x,ae.y=Z.y,ae.z=Z.z,this._computeParticleRotation||this.billboard){const B=r.m;W[0]=B[0],W[1]=B[1],W[2]=B[2],W[3]=B[4],W[4]=B[5],W[5]=B[6],W[6]=B[8],W[7]=B[9],W[8]=B[10]}const N=m[11];for(z.translateFromPivot?N.setAll(0):N.copyFrom(ue),V=0;V0)for(let a=0;a(this._isReady=!0,this._buildMesh(e)))}_buildMesh(e){this.nbParticles===0&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new at;t.set(this._positions32,$.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,$.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,$.ColorKind));const r=new Ee(this.name,this._scene);t.applyToMesh(r,this._updatable),this.mesh=r,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let n=e;return n||(n=new et("point cloud material",this._scene),n.emissiveColor=new Re(i,i,i),n.disableLighting=!0,n.pointsCloud=!0,n.pointSize=this._size),r.material=n,new Promise(a=>a(r))}_addParticle(e,t,i,r){const n=new dYe(e,t,i,r,this);return this.particles.push(n),n}_randomUnitVector(e){e.position=new D(Math.random(),Math.random(),Math.random()),e.color=new Ze(1,1,1,1)}_getColorIndicesForCoord(e,t,i,r){const n=e._groupImageData,a=i*(r*4)+t*4,o=[a,a+1,a+2,a+3],l=o[0],c=o[1],u=o[2],h=o[3],d=n[l],f=n[c],p=n[u],m=n[h];return new Ze(d/255,f/255,p/255,m)}_setPointsColorOrUV(e,t,i,r,n,a,o,l){l=l??0,i&&e.updateFacetData();const u=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData($.PositionKind);const d=e.getIndices(),f=e.getVerticesData($.UVKind+(l?l+1:"")),p=e.getVerticesData($.ColorKind),m=D.Zero();e.computeWorldMatrix();const g=e.getWorldMatrix();if(!g.isIdentity()){h=h.slice(0);for(let Ni=0;Ni1&&(jt=1),cs<0&&(cs=0),cs>1&&(cs=1),Re.HSVtoRGBToRef(As,jt,cs,or),Ti.set(or.r,or.g,or.b,1)):Ti=Et.set(Math.random(),Math.random(),Math.random(),1),mi.color=new Ze(Ti.x,Ti.y,Ti.z,Ti.w),this._colors.push(Ti.x,Ti.y,Ti.z,Ti.w))}}_colorFromTexture(e,t,i){if(e.material===null){fe.Warn(e.name+"has no material."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const n=e.material.getActiveTextures();if(n.length===0){fe.Warn(e.name+"has no usable texture."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const a=e.clone();a.setEnabled(!1),this._promises.push(new Promise(o=>{$r.WhenAllReady(n,()=>{let l=t._textureNb;l<0&&(l=0),l>n.length-1&&(l=n.length-1);const c=()=>{t._groupImgWidth=n[l].getSize().width,t._groupImgHeight=n[l].getSize().height,this._setPointsColorOrUV(a,t,i,!0,!0,void 0,void 0,n[l].coordinatesIndex),a.dispose(),o()};t._groupImageData=null;const u=n[l].readPixels();u?u.then(h=>{t._groupImageData=h,c()}):c()})}))}_calculateDensity(e,t,i){let r,n,a,o,l,c,u,h,d,f,p,m;const g=D.Zero(),_=D.Zero(),y=D.Zero(),v=D.Zero(),x=D.Zero(),A=D.Zero();let b;const C=[];let T=0;const w=i.length/3;for(let R=0;R0;R--){const I=C[R];if(I===0)P[R]=0;else{const k=(I-C[R-1])/I*M,V=Math.floor(k),H=k-V,j=+(Math.random()3)&&(a=0);const o=e.getVerticesData($.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const c=new ZQ(this._groupCounter,null);switch(c._groupDensity=this._calculateDensity(t,o,l),a===2?c._textureNb=r||0:r=r||new Ze(1,1,1,1),a){case 2:this._colorFromTexture(e,c,!1);break;case 1:this._setPointsColorOrUV(e,c,!1,!1,!1);break;case 0:this._setPointsColorOrUV(e,c,!1);break;case 3:this._setPointsColorOrUV(e,c,!1,void 0,void 0,r,n);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,r,n){let a=i||0;(isNaN(a)||a<0||a>3)&&(a=0);const o=e.getVerticesData($.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const c=new ZQ(this._groupCounter,null);switch(c._groupDensity=this._calculateDensity(t,o,l),a===2?c._textureNb=r||0:r=r||new Ze(1,1,1,1),a){case 2:this._colorFromTexture(e,c,!0);break;case 1:this._setPointsColorOrUV(e,c,!0,!1,!1);break;case 0:this._setPointsColorOrUV(e,c,!0);break;case 3:this._setPointsColorOrUV(e,c,!0,void 0,void 0,r,n);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){var v,x;if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const r=se.Matrix[0],n=this.mesh,a=this._colors32,o=this._positions32,l=this._uvs32,c=se.Vector3,u=c[5].copyFromFloats(1,0,0),h=c[6].copyFromFloats(0,1,0),d=c[7].copyFromFloats(0,0,1),f=c[8].setAll(Number.MAX_VALUE),p=c[9].setAll(-Number.MAX_VALUE);he.IdentityToRef(r);let m=0;if((v=this.mesh)!=null&&v.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const A=(x=this.mesh)==null?void 0:x.getBoundingInfo();A&&(f.copyFrom(A.minimum),p.copyFrom(A.maximum))}m=0;let g=0,_=0,y=0;for(let A=e;A<=t;A++){const b=this.particles[A];m=b.idx,g=3*m,_=4*m,y=2*m,this.updateParticle(b);const C=b._rotationMatrix,T=b.position,w=b._globalPosition;if(this._computeParticleRotation&&b.getRotationMatrix(r),b.parentId!==null){const W=this.particles[b.parentId],Z=W._rotationMatrix,q=W._globalPosition,ie=T.x*Z[1]+T.y*Z[4]+T.z*Z[7],ae=T.x*Z[0]+T.y*Z[3]+T.z*Z[6],ue=T.x*Z[2]+T.y*Z[5]+T.z*Z[8];if(w.x=q.x+ae,w.y=q.y+ie,w.z=q.z+ue,this._computeParticleRotation){const ce=r.m;C[0]=ce[0]*Z[0]+ce[1]*Z[3]+ce[2]*Z[6],C[1]=ce[0]*Z[1]+ce[1]*Z[4]+ce[2]*Z[7],C[2]=ce[0]*Z[2]+ce[1]*Z[5]+ce[2]*Z[8],C[3]=ce[4]*Z[0]+ce[5]*Z[3]+ce[6]*Z[6],C[4]=ce[4]*Z[1]+ce[5]*Z[4]+ce[6]*Z[7],C[5]=ce[4]*Z[2]+ce[5]*Z[5]+ce[6]*Z[8],C[6]=ce[8]*Z[0]+ce[9]*Z[3]+ce[10]*Z[6],C[7]=ce[8]*Z[1]+ce[9]*Z[4]+ce[10]*Z[7],C[8]=ce[8]*Z[2]+ce[9]*Z[5]+ce[10]*Z[8]}}else if(w.x=0,w.y=0,w.z=0,this._computeParticleRotation){const W=r.m;C[0]=W[0],C[1]=W[1],C[2]=W[2],C[3]=W[4],C[4]=W[5],C[5]=W[6],C[6]=W[8],C[7]=W[9],C[8]=W[10]}const M=c[11];b.translateFromPivot?M.setAll(0):M.copyFrom(b.pivot);const R=c[0];R.copyFrom(b.position);const I=R.x-b.pivot.x,L=R.y-b.pivot.y,k=R.z-b.pivot.z;let V=I*C[0]+L*C[3]+k*C[6],H=I*C[1]+L*C[4]+k*C[7],j=I*C[2]+L*C[5]+k*C[8];V+=M.x,H+=M.y,j+=M.z;const z=o[g]=w.x+u.x*V+h.x*H+d.x*j,K=o[g+1]=w.y+u.y*V+h.y*H+d.y*j,U=o[g+2]=w.z+u.z*V+h.z*H+d.z*j;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(z,K,U),p.maximizeInPlaceFromFloats(z,K,U)),this._computeParticleColor&&b.color){const W=b.color,Z=this._colors32;Z[_]=W.r,Z[_+1]=W.g,Z[_+2]=W.b,Z[_+3]=W.a}if(this._computeParticleTexture&&b.uv){const W=b.uv,Z=this._uvs32;Z[y]=W.x,Z[y+1]=W.y}}return n&&(i&&(this._computeParticleColor&&n.updateVerticesData($.ColorKind,a,!1,!1),this._computeParticleTexture&&n.updateVerticesData($.UVKind,l,!1,!1),n.updateVerticesData($.PositionKind,o,!1,!1)),this._computeBoundingBox&&(n.hasBoundingInfo?n.getBoundingInfo().reConstruct(f,p,n._worldMatrix):n.buildBoundingInfo(f,p,n._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){var e;(e=this.mesh)==null||e.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){var e;return this._isVisibilityBoxLocked||(e=this.mesh)==null||e.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new D(-t,-t,-t),new D(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}const fYe="particlesPixelShader",pYe=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; #include #include #include #include #include #ifdef RAMPGRADIENT varying vec4 remapRanges;uniform sampler2D rampSampler; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; #ifdef RAMPGRADIENT float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); #endif #ifdef BLENDMULTIPLYMODE float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); #endif #include #include(color,baseColor) #ifdef IMAGEPROCESSINGPOSTPROCESS baseColor.rgb=toLinearSpace(baseColor.rgb); #else #ifdef IMAGEPROCESSING baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); #endif #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[fYe]=pYe;const mYe={name:fYe,shader:pYe},QMt=Object.freeze(Object.defineProperty({__proto__:null,particlesPixelShader:mYe},Symbol.toStringTag,{value:"Module"})),gYe="particlesVertexShader",_Ye=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; #ifdef ANIMATESHEET attribute float cellIndex; #endif #ifndef BILLBOARD attribute vec3 direction; #endif #ifdef BILLBOARDSTRETCHED attribute vec3 direction; #endif #ifdef RAMPGRADIENT attribute vec4 remapData; #endif attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; #ifdef ANIMATESHEET uniform vec3 particlesInfos; #endif varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; #ifdef RAMPGRADIENT varying vec4 remapRanges; #endif #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform mat4 invView; #endif #include #include #include #ifdef BILLBOARD uniform vec3 eyePosition; #endif vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} #ifdef BILLBOARDSTRETCHED vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); #ifdef BILLBOARDSTRETCHED_LOCAL vec3 row1=direction; #else vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); #endif mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; #ifdef BILLBOARD vec3 rotatedCorner; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; #else rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; #endif #ifdef RAMPGRADIENT remapRanges=remapData; #endif gl_Position=projection*vec4(viewPos,1.0); #else vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); #endif vColor=color; #ifdef ANIMATESHEET float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; #else vUV=offset; #endif #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[gYe]=_Ye;const vYe={name:gYe,shader:_Ye},yYe=Object.freeze(Object.defineProperty({__proto__:null,particlesVertexShader:vYe},Symbol.toStringTag,{value:"Module"})),xYe="particlesPixelShader",AYe=`varying vUV: vec2f;varying vColor: vec4f;uniform textureMask: vec4f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #include #include #include #include #include #ifdef RAMPGRADIENT varying remapRanges: vec4f;var rampSamplerSampler: sampler;var rampSampler: texture_2d; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include var textureColor: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV);var baseColor: vec4f=(textureColor*uniforms.textureMask+( vec4f(1.,1.,1.,1.)-uniforms.textureMask))*input.vColor; #ifdef RAMPGRADIENT var alpha: f32=baseColor.a;var remappedColorIndex: f32=clamp((alpha-input.remapRanges.x)/input.remapRanges.y,0.0,1.0);var rampColor: vec4f=textureSample(rampSampler,rampSamplerSampler,vec2f(1.0-remappedColorIndex,0.));baseColor=vec4f(baseColor.rgb*rampColor.rgb,baseColor.a);var finalAlpha: f32=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-input.remapRanges.z)/input.remapRanges.w,0.0,1.0); #endif #ifdef BLENDMULTIPLYMODE var sourceAlpha: f32=input.vColor.a*textureColor.a;baseColor=vec4f(baseColor.rgb*sourceAlpha+ vec3f(1.0)*(1.0-sourceAlpha),baseColor.a); #endif #include #include(color,baseColor) #ifdef IMAGEPROCESSINGPOSTPROCESS baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a); #else #ifdef IMAGEPROCESSING baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);baseColor=applyImageProcessing(baseColor); #endif #endif fragmentOutputs.color=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[xYe]=AYe;const bYe={name:xYe,shader:AYe},$Mt=Object.freeze(Object.defineProperty({__proto__:null,particlesPixelShaderWGSL:bYe},Symbol.toStringTag,{value:"Module"})),CYe="particlesVertexShader",SYe=`attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f; #ifdef ANIMATESHEET attribute cellIndex: f32; #endif #ifndef BILLBOARD attribute direction: vec3f; #endif #ifdef BILLBOARDSTRETCHED attribute direction: vec3f; #endif #ifdef RAMPGRADIENT attribute remapData: vec4f; #endif attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f; #ifdef ANIMATESHEET uniform particlesInfos: vec3f; #endif varying vUV: vec2f;varying vColor: vec4f;varying vPositionW: vec3f; #ifdef RAMPGRADIENT varying remapRanges: vec4f; #endif #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform invView: mat4x4f; #endif #include #include #include #ifdef BILLBOARD uniform eyePosition: vec3f; #endif fn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;} #ifdef BILLBOARDSTRETCHED fn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(vertexInputs.direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); #ifdef BILLBOARDSTRETCHED_LOCAL var row1: vec3f=vertexInputs.direction; #else var crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z); #endif var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return input.position+alignedCorner;} #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var cornerPos: vec2f;cornerPos=( vec2f(input.offset.x-0.5,input.offset.y -0.5)-uniforms.translationPivot)*input.size; #ifdef BILLBOARD var rotatedCorner: vec3f; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=input.position-uniforms.eyePosition;yaxis.y=0.;vertexOutputs.vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz; #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var toCamera: vec3f=input.position-uniforms.eyePosition;vertexOutputs.vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz; #else rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var viewPos: vec3f=(uniforms.view* vec4f(input.position,1.0)).xyz+rotatedCorner;vertexOutputs.vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz; #endif #ifdef RAMPGRADIENT vertexOutputs.remapRanges=input.remapData; #endif vertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0); #else var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=normalize(vertexInputs.direction);vertexOutputs.vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*uniforms.view* vec4f(vertexOutputs.vPositionW,1.0); #endif vertexOutputs.vColor=input.color; #ifdef ANIMATESHEET var rowOffset: f32=floor(input.cellIndex*uniforms.particlesInfos.z);var columnOffset: f32=input.cellIndex-rowOffset/uniforms.particlesInfos.z;var uvScale: vec2f=uniforms.particlesInfos.xy;var uvOffset: vec2f= vec2f(input.offset.x ,1.0-input.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale; #else vertexOutputs.vUV=input.offset; #endif #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) var worldPos: vec4f= vec4f(vertexOutputs.vPositionW,1.0); #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[CYe]=SYe;const EYe={name:CYe,shader:SYe},TYe=Object.freeze(Object.defineProperty({__proto__:null,particlesVertexShaderWGSL:EYe},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(Li.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(s){this._physicsImpostor!==s&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=s,s&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});Li.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};Li.prototype.applyImpulse=function(s,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(s,e),this):this};Li.prototype.setPhysicsLinkWith=function(s,e,t,i){return!this.physicsImpostor||!s.physicsImpostor?this:(this.physicsImpostor.createJoint(s.physicsImpostor,ks.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class kee{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw vi("")}constructor(e,t=kee.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new D(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}setVelocityLimits(e,t){this._physicsPlugin.setVelocityLimits(e,t)}getMaxLinearVelocity(){return this._physicsPlugin.getMaxLinearVelocity()}getMaxAngularVelocity(){return this._physicsPlugin.getMaxAngularVelocity()}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){const r=new Xz;return this._physicsPlugin.raycast(e,t,r,i),r}}var Ede;(function(s){s[s.FREE=0]="FREE",s[s.LIMITED=1]="LIMITED",s[s.LOCKED=2]="LOCKED"})(Ede||(Ede={}));var Tde;(function(s){s[s.LINEAR_X=0]="LINEAR_X",s[s.LINEAR_Y=1]="LINEAR_Y",s[s.LINEAR_Z=2]="LINEAR_Z",s[s.ANGULAR_X=3]="ANGULAR_X",s[s.ANGULAR_Y=4]="ANGULAR_Y",s[s.ANGULAR_Z=5]="ANGULAR_Z",s[s.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(Tde||(Tde={}));var Mde;(function(s){s[s.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",s[s.DISTANCE=2]="DISTANCE",s[s.HINGE=3]="HINGE",s[s.SLIDER=4]="SLIDER",s[s.LOCK=5]="LOCK",s[s.PRISMATIC=6]="PRISMATIC",s[s.SIX_DOF=7]="SIX_DOF"})(Mde||(Mde={}));var Rde;(function(s){s[s.SPHERE=0]="SPHERE",s[s.CAPSULE=1]="CAPSULE",s[s.CYLINDER=2]="CYLINDER",s[s.BOX=3]="BOX",s[s.CONVEX_HULL=4]="CONVEX_HULL",s[s.CONTAINER=5]="CONTAINER",s[s.MESH=6]="MESH",s[s.HEIGHTFIELD=7]="HEIGHTFIELD"})(Rde||(Rde={}));var Ide;(function(s){s[s.NONE=0]="NONE",s[s.VELOCITY=1]="VELOCITY",s[s.POSITION=2]="POSITION"})(Ide||(Ide={}));var Pde;(function(s){s.COLLISION_STARTED="COLLISION_STARTED",s.COLLISION_CONTINUED="COLLISION_CONTINUED",s.COLLISION_FINISHED="COLLISION_FINISHED",s.TRIGGER_ENTERED="TRIGGER_ENTERED",s.TRIGGER_EXITED="TRIGGER_EXITED"})(Pde||(Pde={}));var wde;(function(s){s[s.STATIC=0]="STATIC",s[s.ANIMATED=1]="ANIMATED",s[s.DYNAMIC=2]="DYNAMIC"})(wde||(wde={}));var H1;(function(s){s[s.DISABLED=0]="DISABLED",s[s.TELEPORT=1]="TELEPORT",s[s.ACTION=2]="ACTION"})(H1||(H1={}));var Dde;(function(s){s[s.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",s[s.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",s[s.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"})(Dde||(Dde={}));class Uee{get disablePreStep(){return this._prestepType==H1.DISABLED}set disablePreStep(e){this._prestepType=e?H1.DISABLED:H1.TELEPORT}constructor(e,t,i,r){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disableSync=!1,this._isDisposed=!1,this._shape=null,this._prestepType=H1.DISABLED,!r)return;const n=r.getPhysicsEngine();if(!n)throw new Error("No Physics Engine available.");if(this._physicsEngine=n,n.getPluginVersion()!=2)throw new Error("Plugin version is incorrect. Expected version 2.");const a=n.getPhysicsPlugin();if(!a)throw new Error("No Physics Plugin available.");this._physicsPlugin=a,e.rotationQuaternion||(e.rotationQuaternion=Pe.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t==0;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,n.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}getClassName(){return"PhysicsBody"}clone(e){const t=new Uee(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}getBoundingBox(){return this._physicsPlugin.getBodyBoundingBox(this)}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=e==0,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}setPrestepType(e){this._prestepType=e}getPrestepType(){return this._prestepType}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new D;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new D;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new D;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){var i;if(((i=this._pluginDataInstances)==null?void 0:i.length)>0){const r=t||0,n=this.transformNode._thinInstanceDataStorage.matrixData;n&&e.set(n[r*16+12],n[r*16+13],n[r*16+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,r){this._physicsPlugin.addConstraint(this,e,t,i,r)}syncWithBone(e,t,i,r,n,a){const o=this.transformNode;if(o.rotationQuaternion)if(n){const u=se.Quaternion[0];e.getRotationQuaternionToRef(1,t,u),u.multiplyToRef(n,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const l=se.Vector3[0],c=se.Vector3[1];a||(a=se.Vector3[2],a.x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,c),e.getAbsolutePositionToRef(t,l),r==null&&i&&(r=i.length()),r!=null&&(l.x+=c.x*r,l.y+=c.y*r,l.z+=c.z*r),o.setAbsolutePosition(l)}iterateOverAllInstances(e){var t;if(((t=this._pluginDataInstances)==null?void 0:t.length)>0)for(let i=0;i{this.dispose()})}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new ed(new D(-.5,-.5,-.5),new D(.5,.5,.5))}_hasVertices(e){return(e==null?void 0:e.getTotalVertices())>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=se.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.absoluteScaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=se.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.absoluteScaling),!this._options.center){const r=new D;r.copyFrom(e.center),r.multiplyInPlace(this.transformNode.absoluteScaling),this._options.center=r}switch(this.type){case 0:!this._options.radius&&At.WithinEpsilon(t.x,t.y,1e-4)&&At.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(fe.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case 1:{const r=t.x/2;this._options.radius=this._options.radius??r,this._options.pointA=this._options.pointA??new D(0,i.y+r,0),this._options.pointB=this._options.pointB??new D(0,i.y+t.y-r,0)}break;case 2:{const r=t.x/2;this._options.radius=this._options.radius??r,this._options.pointA=this._options.pointA??new D(0,i.y,0),this._options.pointB=this._options.pointB??new D(0,i.y+t.y,0)}break;case 6:case 4:case 7:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case 3:this._options.extents=this._options.extents??new D(t.x,t.y,t.z),this._options.rotation=this._options.rotation??Pe.Identity();break}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class u8t{}class h8t{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=3,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=3,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()}),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach(e=>{e.linkTransformNode(null)});for(let e=0;e{e.dispose()})}}class d8t{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=se.Matrix[0];if(he.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof Ee?this._addMesh(e,i):e instanceof C0&&this._addMesh(e.sourceMesh,i),t){const r=se.Matrix[1];e.computeWorldMatrix().invertToRef(r);const n=se.Matrix[2];r.multiplyToRef(i,n),e.getChildMeshes(!1).filter(o=>!o.physicsBody).forEach(o=>{const l=o.computeWorldMatrix(),c=se.Matrix[3];l.multiplyToRef(n,c),o instanceof Ee?this._addMesh(o,c):o instanceof C0&&this._addMesh(o.sourceMesh,c)})}}_addMesh(e,t){const i=e.getVerticesData($.PositionKind)||[],r=i.length/3,n=this._vertices.length;for(let a=0;a0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){var a;const r=((a=i._thinInstanceDataStorage)==null?void 0:a.instancesCount)??0,n=i._thinInstanceDataStorage.matrixData;n&&(this._createOrUpdateBodyInstances(e,t,n,0,r,!1),e._pluginDataInstances.forEach((o,l)=>{this._bodies.set(o.hpBodyId[0],{body:e,index:l})}))}_createOrUpdateBodyInstances(e,t,i,r,n,a){const o=se.Quaternion[0],l=he.Identity();for(let c=r;cn){this._createOrUpdateBodyInstances(e,a,r,n,i,!1);const c=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];c[0]||(c[0]=(l=e.shape)==null?void 0:l._pluginData[0]);for(let u=n;u{this._hknp.HP_Body_SetEventMask(r.hpBodyId,t)},i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:D.FromArray(e[0]),mass:e[1],inertia:D.FromArray(e[2]),inertiaOrientation:Pe.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),i.mass!=null&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case 0:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case 1:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case 2:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC);break}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,r=>{this._internalSetMotionType(r,t)},i)}getMotionType(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(r){case this._hknp.MotionType.STATIC:return 0;case this._hknp.MotionType.KINEMATIC:return 1;case this._hknp.MotionType.DYNAMIC:return 2}throw new Error("Unknown motion type: "+r)}setActivationControl(e,t){switch(t){case 1:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case 2:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case 0:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED);break}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const i=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(i[0]==this._hknp.Result.RESULT_OK)return i[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(r)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,r=>{r.userMassProps=t,this._internalUpdateMassProperties(r)},i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(r)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetLinearDamping(r.hpBodyId,t)},i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetAngularDamping(r.hpBodyId,t)},i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetLinearVelocity(r.hpBodyId,this._bVecToV3(t))},i)}getLinearVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),n=this._hknp.HP_Body_GetLinearVelocity(r.hpBodyId)[1];this._v3ToBvecRef(n,t)}_applyToBodyOrInstances(e,t,i){var r;if(((r=e._pluginDataInstances)==null?void 0:r.length)>0&&i===void 0)for(let n=0;n{this._hknp.HP_Body_ApplyImpulse(n.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))},r)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_ApplyAngularImpulse(r.hpBodyId,this._bVecToV3(t))},i)}applyForce(e,t,i,r){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,r)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetAngularVelocity(r.hpBodyId,this._bVecToV3(t))},i)}getAngularVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),n=this._hknp.HP_Body_GetAngularVelocity(r.hpBodyId)[1];this._v3ToBvecRef(n,t)}setPhysicsBodyTransformation(e,t){if(e.getPrestepType()==H1.TELEPORT){const i=e.transformNode;if(e.numInstances>0){const n=i._thinInstanceDataStorage.matrixData;if(!n)return;const a=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),n,0,a,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}else e.getPrestepType()==H1.ACTION?this.setTargetTransform(e,t.absolutePosition,t.absoluteRotationQuaternion):e.getPrestepType()==H1.DISABLED?fe.Warn("Prestep type is set to DISABLED. Unable to set physics body transformation."):fe.Warn("Invalid prestep type set to physics body.")}setTargetTransform(e,t,i,r){this._applyToBodyOrInstances(e,n=>{this._hknp.HP_Body_SetTargetQTransform(n.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])},r)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,r=>{this._hknp.HP_Body_SetGravityFactor(r.hpBodyId,t)},i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}_createOptionsFromGroundMesh(e){const t=e.groundMesh;if(!t)return;let i=t.getVerticesData($.PositionKind);const r=t.computeWorldMatrix(!0),n=[];let a;for(a=0;a0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],r=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(r[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const n=this._hknp.HP_DebugGeometry_GetInfo(r[1])[1],a=new Float32Array(this._hknp.HEAPU8.buffer,n[0],n[1]*3),o=new Uint32Array(this._hknp.HEAPU8.buffer,n[2],n[3]*3),l=a.slice(0),c=o.slice(0);return this._hknp.HP_DebugGeometry_Release(r[1]),{positions:l,indices:c}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,r,n){const a=e.type,o=e.options;if(!a||!o){fe.Warn("No constraint type or options. Constraint is invalid.");return}if(t._pluginDataInstances.length>0&&r===void 0||i._pluginDataInstances.length>0&&n===void 0){fe.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");return}e._pluginData=e._pluginData??[];const l=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(l);const c=this._getPluginReference(t,r).hpBodyId,u=this._getPluginReference(i,n).hpBodyId;this._hknp.HP_Constraint_SetParentBody(l,c),this._hknp.HP_Constraint_SetChildBody(l,u),this._constraintToBodyIdPair.set(l[0],[c[0],u[0]]);const h=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(D.Zero()),d=o.axisA??new D(1,0,0),f=this._tmpVec3[0];o.perpAxisA?f.copyFrom(o.perpAxisA):d.getNormalToRef(f),this._hknp.HP_Constraint_SetAnchorInParent(l,h,this._bVecToV3(d),this._bVecToV3(f));const p=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(D.Zero()),m=o.axisB??new D(1,0,0),g=this._tmpVec3[0];if(o.perpAxisB?g.copyFrom(o.perpAxisB):m.getNormalToRef(g),this._hknp.HP_Constraint_SetAnchorInChild(l,p,this._bVecToV3(m),this._bVecToV3(g)),e._initOptions||(e._initOptions={axisA:d.clone(),axisB:m.clone(),perpAxisA:f.clone(),perpAxisB:g.clone(),pivotA:new D(h[0],h[1],h[2]),pivotB:new D(p[0],p[1],p[2])}),a==5)this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==2){const y=o.maxDistance||0,v=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(l,v,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(l,v,y),this._hknp.HP_Constraint_SetAxisMaxLimit(l,v,y)}else if(a==3)this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==6)this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==4)this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==1)this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(l,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(a==7){const y=e;for(const v of y.limits){const x=this._constraintAxisToNative(v.axis);(v.minLimit??-1)==0&&(v.maxLimit??-1)==0?this._hknp.HP_Constraint_SetAxisMode(l,x,this._hknp.ConstraintAxisLimitMode.LOCKED):(v.minLimit!=null&&(this._hknp.HP_Constraint_SetAxisMode(l,x,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(l,x,v.minLimit)),v.maxLimit!=null&&(this._hknp.HP_Constraint_SetAxisMode(l,x,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(l,x,v.maxLimit))),v.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(l,x,v.stiffness),v.damping&&this._hknp.HP_Constraint_SetAxisDamping(l,x,v.damping)}}else throw new Error("Unsupported Constraint Type.");const _=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(l,_),this._hknp.HP_Constraint_SetEnabled(l,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const r=this._constraintToBodyIdPair.get(i[0]);if(r){const n=this._bodies.get(r[0]),a=this._bodies.get(r[1]);n&&a&&t.push({parentBody:n.body,parentBodyIndex:n.index,childBody:a.body,childBodyIndex:a.index})}}return t}addConstraint(e,t,i,r,n){this.initConstraint(i,e,t,r,n)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return t?this._hknp.HP_Constraint_GetEnabled(t)[1]:!1}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return t?this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]:!1}setAxisFriction(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(r,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(r,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const r=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(r)}return null}setAxisMinLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(r,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(r,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(r,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(r,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(r,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i==null?void 0:i.body,t.bodyIndex=i==null?void 0:i.index;const r=this._shapes.get(e[1][0]);t.shape=r;const n=e[3],a=e[4],o=e[5];t.setHitData({x:a[0],y:a[1],z:a[2]},{x:n[0],y:n[1],z:n[2]},o)}raycast(e,t,i,r){const n=(r==null?void 0:r.membership)??-1,a=(r==null?void 0:r.collideWith)??-1;i.reset(e,t);const o=!1,l=[BigInt(0)],c=[this._bVecToV3(e),this._bVecToV3(t),[n,a],o,l];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,c),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,u]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(u,i),i.calculateHitDistance()}}pointProximity(e,t){var o,l;const i=((o=e==null?void 0:e.collisionFilter)==null?void 0:o.membership)??-1,r=((l=e==null?void 0:e.collisionFilter)==null?void 0:l.collideWith)??-1;t.reset();const n=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[this._bVecToV3(e.position),e.maxDistance,[i,r],e.shouldHitTriggers,n];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[c,u]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(u,t),t.setHitDistance(c)}}shapeProximity(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,n=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[r,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,n];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[o,l,c]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(l,t),this._populateHitData(c,i),t.setHitDistance(o),i.setHitDistance(o)}}shapeCast(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,n=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[r,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,n];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[o,l,c]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(l,t),this._populateHitData(c,i),t.setHitFraction(o),i.setHitFraction(o)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new Ae,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new Ae,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach(r=>{this._hknp.HP_Body_SetEventMask(r.hpBodyId,t?i:0)}):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let r=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];r=t?r|this._hknp.EventType.COLLISION_FINISHED.value:r&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach(n=>{this._hknp.HP_Body_SetEventMask(n.hpBodyId,r)}):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,r)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new _Me;for(;e;){_Me.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),r=this._bodies.get(t.bodyIdB);if(i&&r){const n={collider:i.body,colliderIndex:i.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(n)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new gMe,i=Number(this.world);for(;e;){gMe.readToRef(this._hknp.HEAPU8.buffer,e,t);const r=this._bodies.get(t.contactOnA.bodyId),n=this._bodies.get(t.contactOnB.bodyId);if(r&&n){const a={collider:r.body,colliderIndex:r.index,collidedAgainst:n.body,collidedAgainstIndex:n.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(a.type==="COLLISION_FINISHED")this.onCollisionEndedObservable.notifyObservers(a);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const o=D.Dot(this._tmpVec3[0],t.contactOnA.normal);a.point=t.contactOnA.position,a.distance=o,a.impulse=t.impulseApplied,a.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(a)}if(this._bodyCollisionObservable.size&&a.type!=="COLLISION_FINISHED"){const o=this._bodyCollisionObservable.get(t.contactOnA.bodyId),l=this._bodyCollisionObservable.get(t.contactOnB.bodyId);t.contactOnA.position.subtractToRef(t.contactOnB.position,this._tmpVec3[0]);const c=D.Dot(this._tmpVec3[0],t.contactOnB.normal);if(o&&o.notifyObservers(a),l){const u={collider:n.body,colliderIndex:n.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnB.position,distance:c,impulse:t.impulseApplied,normal:t.contactOnB.normal,type:this._nativeCollisionValueToCollisionType(t.type)};l.notifyObservers(u)}}else if(this._bodyCollisionEndedObservable.size){const o=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),l=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);t.contactOnA.position.subtractToRef(t.contactOnB.position,this._tmpVec3[0]);const c=D.Dot(this._tmpVec3[0],t.contactOnB.normal);if(o&&o.notifyObservers(a),l){const u={collider:n.body,colliderIndex:n.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnB.position,distance:c,impulse:t.impulseApplied,normal:t.contactOnB.normal,type:this._nativeCollisionValueToCollisionType(t.type)};l.notifyObservers(u)}}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._queryCollector&&(this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=void 0),this.world&&(this._hknp.HP_World_Release(this.world),this.world=void 0)}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case 2:return this._hknp.ConstraintMotorType.POSITION;case 1:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return 2;case this._hknp.ConstraintMotorType.VELOCITY:return 1}return 0}_materialCombineToNative(e){switch(e){case 0:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case 1:return this._hknp.MaterialCombine.MINIMUM;case 2:return this._hknp.MaterialCombine.MAXIMUM;case 3:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case 4:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return 0;case this._hknp.MaterialCombine.MINIMUM:return 1;case this._hknp.MaterialCombine.MAXIMUM:return 2;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return 3;case this._hknp.MaterialCombine.MULTIPLY:return 4;default:return}}_constraintAxisToNative(e){switch(e){case 0:return this._hknp.ConstraintAxis.LINEAR_X;case 1:return this._hknp.ConstraintAxis.LINEAR_Y;case 2:return this._hknp.ConstraintAxis.LINEAR_Z;case 3:return this._hknp.ConstraintAxis.ANGULAR_X;case 4:return this._hknp.ConstraintAxis.ANGULAR_Y;case 5:return this._hknp.ConstraintAxis.ANGULAR_Z;case 6:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return 0;case this._hknp.ConstraintAxisLimitMode.LIMITED:return 1;case this._hknp.ConstraintAxisLimitMode.LOCKED:return 2}return 0}_limitModeToNative(e){switch(e){case 0:return this._hknp.ConstraintAxisLimitMode.FREE;case 1:return this._hknp.ConstraintAxisLimitMode.LIMITED;case 2:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return"COLLISION_STARTED";case this._hknp.EventType.COLLISION_FINISHED.value:return"COLLISION_FINISHED";case this._hknp.EventType.COLLISION_CONTINUED.value:return"COLLISION_CONTINUED"}return"COLLISION_STARTED"}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return"TRIGGER_ENTERED";case 16:return"TRIGGER_EXITED"}return"TRIGGER_ENTERED"}}gt.prototype.getPhysicsEngine=function(){return this._physicsEngine};gt.prototype.enablePhysics=function(s=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(ot.NAME_PHYSICSENGINE);t||(t=new p8t(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new j1e(s,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new kee(s,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return fe.Error(i.message),!1}};gt.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};gt.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};gt.prototype.deleteCompoundImpostor=function(s){const e=s.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};gt.prototype._advancePhysicsEngineStep=function(s){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=s;this._physicsTimeAccumulator>e;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=e;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(s/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class p8t{constructor(e){this.name=ot.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new Ae,this.scene.onAfterPhysicsObservable=new Ae,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?this.scene._physicsEngine.getTimeStep()*1e3:1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(_t.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(s){this._physicsBody!==s&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=s,s&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});_t.prototype.getPhysicsBody=function(){return this.physicsBody};_t.prototype.applyImpulse=function(s,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(s,e),this};_t.prototype.applyAngularImpulse=function(s){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(s),this};class DS{static GetContactPointToRef(e,t,i,r,n){const a=e.getScene().getPhysicsEngine(),o=a==null?void 0:a.getPluginVersion();if(o===1){const c=new $i(t,i).intersectsMesh(e);if(c.hit&&c.pickedPoint)return r.copyFrom(c.pickedPoint),!0}else if(o===2)return e.physicsBody.getObjectCenterWorldToRef(r,n),!0;return!1}static HasAppliedForces(e,t){var i,r;return e.getMotionType(t)===0||(((i=e.getMassProperties(t))==null?void 0:i.mass)??0)===0||((r=e.transformNode)==null?void 0:r.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){const n=se.Vector3[0];return e.subtractToRef(t,n),Math.abs(n.x)<=i&&Math.abs(n.z)<=i&&n.y>=0&&n.y<=r}}class m8t{constructor(e){if(this._hitData={force:new D,contactPoint:new D,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),!this._physicsEngine){fe.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.");return}}applyRadialExplosionImpulse(e,t,i,r){if(!this._physicsEngine)return fe.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;let n=!1;if(typeof t=="number"){const l=t;t=new fP,t.radius=l,t.strength=i??t.strength,t.falloff=r??t.falloff}else n=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const a=new vMe(this._scene,t),o=this._hitData;if(this._physicsEngine.getPluginVersion()===1){const l=Array();this._physicsEngine.getImpostors().forEach(u=>{a.getImpostorHitData(u,e,o)&&(u.applyImpulse(o.force,o.contactPoint),n&&l.push({impostor:u,hitData:this._copyPhysicsHitData(o)}))}),a.triggerAffectedImpostorsCallback(l)}else this._applicationForBodies(a,e,o,n,(l,c)=>{l.applyImpulse(c.force,c.contactPoint,c.instanceIndex)});return a.dispose(!1),a}applyRadialExplosionForce(e,t,i,r){if(!this._physicsEngine)return fe.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;let n=!1;if(typeof t=="number"){const l=t;t=new fP,t.radius=l,t.strength=i??t.strength,t.falloff=r??t.falloff}else n=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const a=new vMe(this._scene,t),o=this._hitData;if(this._physicsEngine.getPluginVersion()===1){const l=Array();this._physicsEngine.getImpostors().forEach(u=>{a.getImpostorHitData(u,e,o)&&(u.applyForce(o.force,o.contactPoint),n&&l.push({impostor:u,hitData:this._copyPhysicsHitData(o)}))}),a.triggerAffectedImpostorsCallback(l)}else this._applicationForBodies(a,e,o,n,(l,c)=>{l.applyForce(c.force,c.contactPoint,c.instanceIndex)});return a.dispose(!1),a}_applicationForBodies(e,t,i,r,n){const a=Array(),o=this._physicsEngine.getBodies();for(const l of o)l.iterateOverAllInstances((c,u)=>{e.getBodyHitData(c,t,i,u)&&(n(c,i),r&&a.push({body:c,hitData:this._copyPhysicsHitData(i)}))});e.triggerAffectedBodiesCallback(a)}gravitationalField(e,t,i,r){if(!this._physicsEngine)return fe.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;if(typeof t=="number"){const a=t;t=new fP,t.radius=a,t.strength=i??t.strength,t.falloff=r??t.falloff}const n=new g8t(this,this._scene,e,t);return n.dispose(!1),n}updraft(e,t,i,r,n){if(!this._physicsEngine)return fe.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;if(typeof t=="number"){const o=t;t=new G_e,t.radius=o,t.strength=i??t.strength,t.height=r??t.height,t.updraftMode=n??t.updraftMode}const a=new zee(this._scene,e,t);return a.dispose(!1),a}vortex(e,t,i,r){if(!this._physicsEngine)return fe.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getPluginVersion()===1&&this._physicsEngine.getImpostors().length===0||this._physicsEngine.getPluginVersion()===2&&this._physicsEngine.getBodies().length===0)return null;if(typeof t=="number"){const a=t;t=new W_e,t.radius=a,t.strength=i??t.strength,t.height=r??t.height}const n=new fw(this._scene,e,t);return n.dispose(!1),n}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class vMe{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new fP,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,r){const n=se.Vector3[0];n.copyFrom(t).subtractInPlace(i);const a=se.Vector3[1];if(!DS.GetContactPointToRef(e,i,n,a,r.instanceIndex))return!1;const l=D.Distance(i,a);if(l>this._options.radius)return!1;const c=this._options.falloff===0?this._options.strength:this._options.strength*(1-l/this._options.radius);return n.scaleInPlace(c),r.force.copyFrom(n),r.contactPoint.copyFrom(a),r.distanceFromOrigin=l,!0}getBodyHitData(e,t,i,r){if(DS.HasAppliedForces(e,r))return!1;const n=e.transformNode,a=e.getObjectCenterWorld(r);return i.instanceIndex=r,this._getHitData(n,a,t,i)}getImpostorHitData(e,t,i){if(e.mass===0||e.object.getClassName()!=="Mesh"&&e.object.getClassName()!=="InstancedMesh")return!1;const r=e.object;if(!this._intersectsWithSphere(r,t,this._options.radius))return!1;const n=e.getObjectCenter();return this._getHitData(r,n,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout(()=>{this._dataFetched||this._sphere.dispose()},0))}_prepareSphere(){this._sphere||(this._sphere=kc("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(i*2),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class g8t{constructor(e,t,i,r){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=r,this._dataFetched=!1,this._options={...new fP,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=this._options.strength*-1}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout(()=>{this._dataFetched||this._sphere.dispose()},0))}_tick(){var e;if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const t=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);t&&(this._sphere=(e=t.getData().sphere)==null?void 0:e.clone("radialExplosionEventSphereClone"))}}}class zee{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=D.Zero(),this._originDirection=D.Zero(),this._cylinderPosition=D.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new G_e,...this._options},this._origin.addToRef(new D(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new D(0,this._options.height,0),this._originTop),this._options.updraftMode===1&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),this._physicsEngine.getPluginVersion()===1&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;this._options.updraftMode===1?i=this._originDirection:i=e.subtract(this._originTop);const r=D.Distance(this._origin,e),n=this._options.strength*-1,a=i.multiplyByFloats(n,n,n);t.force.copyFrom(a),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(DS.HasAppliedForces(e))return!1;const r=e.getObjectCenterWorld(i);return DS.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(r,t),!0):!1}_getImpostorHitData(e,t){if(e.mass===0)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){const e=zee._HitData;this._physicsEngine.getPluginVersion()===1?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((i,r)=>{this._getBodyHitData(i,e,r)&&i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=ou("updraftEventCylinder",{height:this._options.height,diameter:this._options.radius*2},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder?(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)):!1}}zee._HitData={force:new D,contactPoint:new D,distanceFromOrigin:0};class fw{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=D.Zero(),this._cylinderPosition=D.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new W_e,...this._options},this._origin.addToRef(new D(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new D(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),this._physicsEngine.getPluginVersion()===1&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){const r=fw._OriginOnPlane;r.set(this._origin.x,t.y,this._origin.z);const n=se.Vector3[0];t.subtractToRef(r,n);const a=se.Vector3[1];if(!DS.GetContactPointToRef(e,r,n,a,i.instanceIndex))return!1;const c=D.Distance(a,r)/this._options.radius,u=se.Vector3[2];a.normalizeToRef(u),c>this._options.centripetalForceThreshold&&u.negateInPlace();let h,d,f;if(c>this._options.centripetalForceThreshold)h=u.x*this._options.centripetalForceMultiplier,d=u.y*this._options.updraftForceMultiplier,f=u.z*this._options.centripetalForceMultiplier;else{const m=D.Cross(r,t).normalize();h=(m.x+u.x)*this._options.centrifugalForceMultiplier,d=this._originTop.y*this._options.updraftForceMultiplier,f=(m.z+u.z)*this._options.centrifugalForceMultiplier}const p=se.Vector3[3];return p.set(h,d,f),p.scaleInPlace(this._options.strength),i.force.copyFrom(p),i.contactPoint.copyFrom(t),i.distanceFromOrigin=c,!0}_getBodyHitData(e,t,i){if(DS.HasAppliedForces(e,i))return!1;const r=e.transformNode,n=e.getObjectCenterWorld(i);return DS.IsInsideCylinder(n,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(r,n,t)):!1}_getImpostorHitData(e,t){if(e.mass===0||e.object.getClassName()!=="Mesh"&&e.object.getClassName()!=="InstancedMesh")return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){const e=fw._HitData;this._physicsEngine.getPluginVersion()===1?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((i,r)=>{this._getBodyHitData(i,e,r)&&i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=ou("vortexEventCylinder",{height:this._options.height,diameter:this._options.radius*2},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}fw._OriginOnPlane=D.Zero();fw._HitData={force:new D,contactPoint:new D,distanceFromOrigin:0};class fP{constructor(){this.radius=5,this.strength=10,this.falloff=0,this.sphere={segments:32,diameter:1}}}class G_e{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=0}}class W_e{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}var Ode;(function(s){s[s.Constant=0]="Constant",s[s.Linear=1]="Linear"})(Ode||(Ode={}));var Nde;(function(s){s[s.Center=0]="Center",s[s.Perpendicular=1]="Perpendicular"})(Nde||(Nde={}));class _8t extends H1e{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class v8t extends H1e{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}class sV extends Ft{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,n,a){super(e,"blackAndWhite",["degree"],null,t,i,r,n,a),this.degree=1,this.onApplyObservable.add(o=>{o.setFloat("degree",this.degree)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>cIt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>lIt),void 0)),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new sV(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}F([X()],sV.prototype,"degree",void 0);ve("BABYLON.BlackAndWhitePostProcess",sV);class Yr{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let i=0;i{const l=n.attachPostProcess(o);this._indicesForCamera[a].push(l)}),this._cameras[a]||(this._cameras[a]=n)}}_detachCameras(e){const t=Me.MakeArray(e||this._cameras);if(t)for(let i=0;i{r.detachPostProcess(o)}),this._cameras[n]&&(this._cameras[n]=null),delete this._indicesForCamera[n]}}_enable(e){const t=Me.MakeArray(e||this._cameras);if(t)for(let i=0;i{r.detachPostProcess(a)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}class Vee extends Ft{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,n,a,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,n,a,null,o,void 0,null,l),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(c=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&c.setTextureFromPostProcess("textureSampler",this._inputPostProcess),c.setFloat("threshold",Math.pow(this.threshold,tP)),c.setFloat("exposure",this._exposure)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>rIt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>iIt),void 0)),super._gatherImports(e,t)}}F([X()],Vee.prototype,"threshold",void 0);ve("BABYLON.ExtractHighlightsPostProcess",Vee);class Gee extends Ft{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,n,a,o,l,c,u=0,h=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],n,a,o,l,c,null,u,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("bloomBlur",i),d.setFloat("bloomWeight",this.weight)}),h||this.updateEffect()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>tIt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>eIt),void 0)),super._gatherImports(e,t)}}F([X()],Gee.prototype,"weight",void 0);ve("BABYLON.BloomMergePostProcess",Gee);class Fde extends Yr{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,r,n=0,a=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new Vee("highlights",1,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n,a),this._blurX=new Ho("horizontal blur",new we(1,0),10,t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n,void 0,a),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Ho("vertical blur",new we(0,1),10,t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n,void 0,a),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new Gee("bloomMerge",this._downscale,this._blurY,i,t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n,a),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{h.setFloat("chromatic_aberration",this.aberrationAmount),h.setFloat("screen_width",t),h.setFloat("screen_height",i),h.setFloat("radialIntensity",this.radialIntensity),h.setFloat2("direction",this.direction.x,this.direction.y),h.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>QRt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>D8t),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new vg(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}F([X()],vg.prototype,"aberrationAmount",void 0);F([X()],vg.prototype,"radialIntensity",void 0);F([X()],vg.prototype,"direction",void 0);F([X()],vg.prototype,"centerPosition",void 0);F([X()],vg.prototype,"screenWidth",void 0);F([X()],vg.prototype,"screenHeight",void 0);ve("BABYLON.ChromaticAberrationPostProcess",vg);class fT extends Ft{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,n,a,o,l=0,c=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,n,a,o,null,l,void 0,null,c),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(u=>{if(!this._depthTexture){fe.Warn("No depth texture set on CircleOfConfusionPostProcess");return}u.setTexture("depthSampler",this._depthTexture);const d=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);u.setFloat("focusDistance",this.focusDistance),u.setFloat("cocPrecalculation",d);const f=this._depthTexture.activeCamera;u.setFloat2("cameraMinMaxZ",f.minZ,f.maxZ-f.minZ)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>JRt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>qRt),void 0)),super._gatherImports(e,t)}set depthTexture(e){this._depthTexture=e}}F([X()],fT.prototype,"lensSize",void 0);F([X()],fT.prototype,"fStop",void 0);F([X()],fT.prototype,"focusDistance",void 0);F([X()],fT.prototype,"focalLength",void 0);ve("BABYLON.CircleOfConfusionPostProcess",fT);class nV extends Ft{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,n,a,o){super(e,"colorCorrection",null,["colorTable"],i,r,n,a,o);const l=(r==null?void 0:r.getScene())||null;this._colorTableTexture=new xe(t,l,!0,!1,xe.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=xe.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=xe.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=c=>{c.setTexture("colorTable",this._colorTableTexture)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>mIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>pIt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new nV(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}F([X()],nV.prototype,"colorTableUrl",void 0);ve("BABYLON.ColorCorrectionPostProcess",nV);class yg extends Ft{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,n,a,o,l=0){super(e,"convolution",["kernel","screenSize"],null,i,r,n,a,o,null,l),this.kernel=t,this.onApply=c=>{c.setFloat2("screenSize",this.width,this.height),c.setArray("kernel",this.kernel)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>fIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>dIt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new yg(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}}yg.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];yg.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];yg.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];yg.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];yg.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];yg.GaussianKernel=[0,1,0,1,1,1,0,1,0];F([X()],yg.prototype,"kernel",void 0);ve("BABYLON.ConvolutionPostProcess",yg);class $k extends Ho{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,n,a,o,l=null,c=xe.BILINEAR_SAMPLINGMODE,u,h,d=0,f=!1,p=5){super(e,i,r,n,a,c=2,u,h,d,`#define DOF 1 `,f,p),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(m=>{l!=null&&m.setTextureFromPostProcess("textureSampler",l),m.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)})}}F([X()],$k.prototype,"direction",void 0);ve("BABYLON.DepthOfFieldBlurPostProcess",$k);class IYe extends Ft{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,n,a,o,l,c,u=0,h=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],n,a,o,l,c,null,u,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((f,p)=>{d.setTextureFromPostProcessOutput("blurStep"+(r.length-p-1),f)})}),h||this.updateEffect()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>ZRt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>$Rt),void 0)),super._gatherImports(e,t)}updateEffect(e=null,t=null,i=null,r,n,a){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+` `),super.updateEffect(e,t,i,r,n,a)}}var Bde;(function(s){s[s.Low=0]="Low",s[s.Medium=1]="Medium",s[s.High=2]="High"})(Bde||(Bde={}));class kde extends Yr{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=0,r=0,n=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const a=e.getEngine(),o=a.isWebGPU||a.version>1?6:5;this._circleOfConfusion=new fT("circleOfConfusion",t,1,null,xe.BILINEAR_SAMPLINGMODE,a,!1,r,n),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,c=15;switch(i){case 2:{l=3,c=51;break}case 1:{l=2,c=31;break}default:{c=15,l=1;break}}const u=c/Math.pow(2,l-1);let h=1;for(let d=0;dPromise.resolve().then(()=>CIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>bIt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new Wee(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}ve("BABYLON.DisplayPassPostProcess",Wee);class aV extends Ft{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,n,a,o){super(e,"filter",["kernelMatrix"],null,i,r,n,a,o),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>yIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>vIt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new aV(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}F([xJ()],aV.prototype,"kernelMatrix",void 0);ve("BABYLON.FilterPostProcess",aV);class pT extends Ft{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,r,n,a,o=0){super(e,"fxaa",["texelSize"],null,t,i,r||xe.BILINEAR_SAMPLINGMODE,n,a,null,o,"fxaa",void 0,!0);const l=this._getDefines();this.updateEffect(l),this.onApplyObservable.add(c=>{const u=this.texelSize;c.setFloat2("texelSize",u.x,u.y)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>aIt),void 0),Ue(()=>Promise.resolve().then(()=>oIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>sIt),void 0),Ue(()=>Promise.resolve().then(()=>nIt),void 0)])),super._gatherImports(e,t)}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?`#define MALI 1 `:null}static _Parse(e,t,i,r){return qe.Parse(()=>new pT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}ve("BABYLON.FxaaPostProcess",pT);class mT extends Ft{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,n,a,o=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,n,a,null,o,void 0,null,l),this.intensity=30,this.animated=!1,this.onApplyObservable.add(c=>{c.setFloat("intensity",this.intensity),c.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>YRt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>XRt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new mT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}F([X()],mT.prototype,"intensity",void 0);F([X()],mT.prototype,"animated",void 0);ve("BABYLON.GrainPostProcess",mT);class y8t extends Ft{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,r,n,a,o=0){super(e,"highlights",null,null,t,i,r,n,a,null,o)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>AIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>xIt),void 0)])),super._gatherImports(e,t)}}class Kee extends Ft{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let i=null;const r=this.getEngine(),n=this.getCamera();if(n)i=n.getScene();else if(r&&r.scenes){const a=r.scenes;i=a[a.length-1]}else i=Rt.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new lr}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,n,a,o=0,l){super(e,"imageProcessing",[],[],t,i,r,n,a,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},l?(l.applyByPostProcess=!0,this._attachImageProcessingConfiguration(l,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=c=>{this.imageProcessingConfiguration.bind(c,this.aspectRatio)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Ue(()=>Promise.resolve().then(()=>KRt),void 0))):t.push(Ue(()=>Promise.resolve().then(()=>HRt),void 0)),super._gatherImports(e,t)}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const r in this._defines){const n=this._defines[r];switch(typeof n){case"number":case"string":e+=`#define ${r} ${n}; `;break;default:n&&(e+=`#define ${r}; `);break}}const t=["textureSampler"],i=["scale"];lr&&(lr.PrepareSamplers(t,this._defines),lr.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}F([X()],Kee.prototype,"_fromLinearSpace",void 0);const x8t="mrtFragmentDeclaration",A8t=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) layout(location=0) out vec4 glFragData[{X}]; #endif `;de.IncludesShadersStore[x8t]=A8t;const PYe="geometryPixelShader",wYe=`#extension GL_EXT_draw_buffers : require #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif precision highp float; #ifdef BUMP varying mat4 vWorldView;varying vec3 vNormalW; #else varying vec3 vNormalV; #endif varying vec4 vViewPos; #if defined(POSITION) || defined(BUMP) varying vec3 vPositionW; #endif #ifdef VELOCITY varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #ifdef NEED_UV varying vec2 vUV; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #if defined(REFLECTIVITY) #if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; #endif #ifdef ALBEDOTEXTURE varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; #endif #ifdef REFLECTIVITYCOLOR uniform vec3 reflectivityColor; #endif #ifdef ALBEDOCOLOR uniform vec3 albedoColor; #endif #ifdef METALLIC uniform float metallic; #endif #if defined(ROUGHNESS) || defined(GLOSSINESS) uniform float glossiness; #endif #endif #if defined(ALPHATEST) && defined(NEED_UV) uniform sampler2D diffuseSampler; #endif #include #include[SCENE_MRT_COUNT] #include #include #include void main() { #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif vec3 normalOutput; #ifdef BUMP vec3 normalW=normalize(vNormalW); #include #ifdef NORMAL_WORLDSPACE normalOutput=normalW; #else normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); #endif #else normalOutput=normalize(vNormalV); #endif #ifdef ENCODE_NORMAL normalOutput=normalOutput*0.5+0.5; #endif #ifdef PREPASS #ifdef PREPASS_DEPTH gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); #endif #ifdef PREPASS_NORMAL gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); #endif #else gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); #endif #ifdef POSITION gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); #endif #ifdef VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); #endif #ifdef REFLECTIVITY vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); #ifdef METALLICWORKFLOW float metal=1.0;float roughness=1.0; #ifdef ORMTEXTURE metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; #endif #ifdef METALLIC metal*=metallic; #endif #ifdef ROUGHNESS roughness*=(1.0-glossiness); #endif reflectivity.a-=roughness;vec3 color=vec3(1.0); #ifdef ALBEDOTEXTURE color=texture2D(albedoSampler,vAlbedoUV).rgb; #ifdef GAMMAALBEDO color=toLinearSpace(color); #endif #endif #ifdef ALBEDOCOLOR color*=albedoColor.xyz; #endif reflectivity.rgb=mix(vec3(0.04),color,metal); #else #if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) reflectivity=texture2D(reflectivitySampler,vReflectivityUV); #ifdef GAMMAREFLECTIVITYTEXTURE reflectivity.rgb=toLinearSpace(reflectivity.rgb); #endif #else #ifdef REFLECTIVITYCOLOR reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; #endif #endif #ifdef GLOSSINESSS reflectivity.a*=glossiness; #endif #endif gl_FragData[REFLECTIVITY_INDEX]=reflectivity; #endif } `;de.ShadersStore[PYe]=wYe;const DYe={name:PYe,shader:wYe},b8t=Object.freeze(Object.defineProperty({__proto__:null,geometryPixelShader:DYe},Symbol.toStringTag,{value:"Module"})),C8t="geometryVertexDeclaration",S8t="uniform mat4 viewProjection;uniform mat4 view;";de.IncludesShadersStore[C8t]=S8t;const E8t="geometryUboDeclaration",T8t=`#include `;de.IncludesShadersStore[E8t]=T8t;const LYe="geometryVertexShader",OYe=`precision highp float; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include<__decl__geometryVertex> #include attribute vec3 position;attribute vec3 normal; #ifdef NEED_UV varying vec2 vUV; #ifdef ALPHATEST uniform mat4 diffuseMatrix; #endif #ifdef BUMP uniform mat4 bumpMatrix;varying vec2 vBumpUV; #endif #ifdef REFLECTIVITY uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; #endif #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #ifdef BUMP varying mat4 vWorldView; #endif #ifdef BUMP varying vec3 vNormalW; #else varying vec3 vNormalV; #endif varying vec4 vViewPos; #if defined(POSITION) || defined(BUMP) varying vec3 vPositionW; #endif #ifdef VELOCITY uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); #ifdef BUMP vWorldView=view*finalWorld;vNormalW=normalUpdated; #else #ifdef NORMAL_WORLDSPACE vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); #else vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); #endif #endif vViewPos=view*worldPos; #if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); #if NUM_BONE_INFLUENCERS>0 mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); #else vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif #if defined(POSITION) || defined(BUMP) vPositionW=worldPos.xyz/worldPos.w; #endif gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); #include #ifdef NEED_UV #ifdef UV1 #if defined(ALPHATEST) && defined(ALPHATEST_UV1) vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #else vUV=uv; #endif #ifdef BUMP_UV1 vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef REFLECTIVITY_UV1 vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef ALBEDO_UV1 vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); #endif #endif #ifdef UV2 #if defined(ALPHATEST) && defined(ALPHATEST_UV2) vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #else vUV=uv2; #endif #ifdef BUMP_UV2 vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); #endif #ifdef REFLECTIVITY_UV2 vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); #endif #ifdef ALBEDO_UV2 vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); #endif #endif #endif #include } `;de.ShadersStore[LYe]=OYe;const NYe={name:LYe,shader:OYe},M8t=Object.freeze(Object.defineProperty({__proto__:null,geometryVertexShader:NYe},Symbol.toStringTag,{value:"Module"})),FYe=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];fo(FYe);class Nr{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===Nr.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===Nr.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===Nr.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===Nr.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===Nr.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case Nr.POSITION_TEXTURE_TYPE:return this._positionIndex;case Nr.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case Nr.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case Nr.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case Nr.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return typeof this._ratioOrDimensions=="object"?1:this._ratioOrDimensions}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ze(0,0,0,0),this._clearDepthColor=new Ze(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._shaderLanguage=0,this._shadersLoaded=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},this._initShaderSourceAsync(),Nr._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!Nr.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Ue(()=>Promise.resolve().then(()=>b5t),void 0),Ue(()=>Promise.resolve().then(()=>A5t),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>M8t),void 0),Ue(()=>Promise.resolve().then(()=>b8t),void 0)]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const r=[],n=[$.PositionKind,$.NormalKind],a=e.getMesh();if(i){let f=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),f=!0),i.bumpTexture&&Je.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let p=!1;i.getClassName()==="PBRMetallicRoughnessMaterial"?(i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),f=!0,p=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),p=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),p=!0),p&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),f=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"))):i.getClassName()==="PBRSpecularGlossinessMaterial"?(i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),f=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),i.glossiness!=null&&r.push("#define GLOSSINESS")):i.getClassName()==="PBRMaterial"?(i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),f=!0,p=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),p=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),p=!0),p?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),f=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),i.microSurface!=null&&r.push("#define GLOSSINESS"))):i.getClassName()==="StandardMaterial"&&(i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}f&&(r.push("#define NEED_UV"),a.isVerticesDataPresent($.UVKind)&&(n.push($.UVKind),r.push("#define UV1")),a.isVerticesDataPresent($.UV2Kind)&&(n.push($.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),this._depthIndex!==-1&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),this._normalIndex!==-1&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),a.useBones&&a.computeBonesUsingShaders&&a.skeleton?(n.push($.MatricesIndicesKind),n.push($.MatricesWeightsKind),a.numBoneInfluencers>4&&(n.push($.MatricesIndicesExtraKind),n.push($.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BONETEXTURE "+a.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(a.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));const o=a.morphTargetManager;let l=0;o&&(l=o.numMaxInfluencers||o.numInfluencers,l>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+l),o.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),rT(n,a,l))),t&&(r.push("#define INSTANCES"),A_(n,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):r.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),t3(i,this._scene,r);const c=this._scene.getEngine(),u=e._getDrawWrapper(void 0,!0),h=u.defines,d=r.join(` `);return h!==d&&u.setEffect(c.createEffect("geometry",{attributes:n,uniformsNames:FYe,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:d,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:l},shaderLanguage:this.shaderLanguage},c),d),u.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[Nr.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[Nr.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[Nr.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[Nr.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[Nr.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices();let n=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?n=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(n=2);const a=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[];for(const g of r)g?(o.push(g.textureType),l.push(g.textureFormat)):(o.push(n),l.push(5));if(this._normalsAreUnsigned=o[Nr.NORMAL_TEXTURE_TYPE]===11||o[Nr.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new nv("gBuffer",a,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:l,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=xe.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=xe.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const c=[!0],u=[!1],h=[!0];for(let g=1;g{g.bindAttachments(this.useSpecificClearForDepthTexture?f:d),g.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(g.bindAttachments(p),g.clear(this._clearDepthColor,!0,!0,!0)),g.bindAttachments(d)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const g=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(g)}});const m=g=>{const _=g.getRenderingMesh(),y=g.getEffectiveMesh(),v=this._scene,x=v.getEngine(),A=g.getMaterial();if(!A)return;if(y._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[y.uniqueId]&&(this._previousTransformationMatrices[y.uniqueId]={world:he.Identity(),viewProjection:v.getTransformMatrix()},_.skeleton)){const w=_.skeleton.getTransformMatrices(_);this._previousBonesTransformationMatrices[_.uniqueId]=this._copyBonesTransformationMatrices(w,new Float32Array(w.length))}const b=_._getInstancesRenderList(g._id,!!g.getReplacementMesh());if(b.mustReturn)return;const C=x.getCaps().instancedArrays&&(b.visibleInstances[g._id]!==null||_.hasThinInstances),T=y.getWorldMatrix();if(this.isReady(g,C)){const w=g._getDrawWrapper();if(!w)return;const P=w.effect;x.enableEffect(w),C||_._bind(g,P,A.fillMode),this._useUbo?($w(P,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(P.setMatrix("viewProjection",v.getTransformMatrix()),P.setMatrix("view",v.getViewMatrix()));let M;const R=_._instanceDataStorage;if(!R.isFrozen&&(A.backFaceCulling||A.sideOrientation!==null)){const I=y._getWorldMatrixDeterminant();M=A._getEffectiveOrientation(_),I<0&&(M=M===Ye.ClockWiseSideOrientation?Ye.CounterClockWiseSideOrientation:Ye.ClockWiseSideOrientation)}else M=R.sideOrientation;if(A._preBind(w,M),A.needAlphaTesting()){const I=A.getAlphaTestTexture();I&&(P.setTexture("diffuseSampler",I),P.setMatrix("diffuseMatrix",I.getTextureMatrix()))}if(A.bumpTexture&&v.getEngine().getCaps().standardDerivatives&&Je.BumpTextureEnabled&&(P.setFloat3("vBumpInfos",A.bumpTexture.coordinatesIndex,1/A.bumpTexture.level,A.parallaxScaleBias),P.setMatrix("bumpMatrix",A.bumpTexture.getTextureMatrix()),P.setTexture("bumpSampler",A.bumpTexture),P.setFloat2("vTangentSpaceParams",A.invertNormalMapX?-1:1,A.invertNormalMapY?-1:1)),this._enableReflectivity&&(A.getClassName()==="PBRMetallicRoughnessMaterial"?(A.metallicRoughnessTexture!==null&&(P.setTexture("reflectivitySampler",A.metallicRoughnessTexture),P.setMatrix("reflectivityMatrix",A.metallicRoughnessTexture.getTextureMatrix())),A.metallic!==null&&P.setFloat("metallic",A.metallic),A.roughness!==null&&P.setFloat("glossiness",1-A.roughness),A.baseTexture!==null&&(P.setTexture("albedoSampler",A.baseTexture),P.setMatrix("albedoMatrix",A.baseTexture.getTextureMatrix())),A.baseColor!==null&&P.setColor3("albedoColor",A.baseColor)):A.getClassName()==="PBRSpecularGlossinessMaterial"?(A.specularGlossinessTexture!==null?(P.setTexture("reflectivitySampler",A.specularGlossinessTexture),P.setMatrix("reflectivityMatrix",A.specularGlossinessTexture.getTextureMatrix())):A.specularColor!==null&&P.setColor3("reflectivityColor",A.specularColor),A.glossiness!==null&&P.setFloat("glossiness",A.glossiness)):A.getClassName()==="PBRMaterial"?(A.metallicTexture!==null&&(P.setTexture("reflectivitySampler",A.metallicTexture),P.setMatrix("reflectivityMatrix",A.metallicTexture.getTextureMatrix())),A.metallic!==null&&P.setFloat("metallic",A.metallic),A.roughness!==null&&P.setFloat("glossiness",1-A.roughness),A.roughness!==null||A.metallic!==null||A.metallicTexture!==null?(A.albedoTexture!==null&&(P.setTexture("albedoSampler",A.albedoTexture),P.setMatrix("albedoMatrix",A.albedoTexture.getTextureMatrix())),A.albedoColor!==null&&P.setColor3("albedoColor",A.albedoColor)):(A.reflectivityTexture!==null?(P.setTexture("reflectivitySampler",A.reflectivityTexture),P.setMatrix("reflectivityMatrix",A.reflectivityTexture.getTextureMatrix())):A.reflectivityColor!==null&&P.setColor3("reflectivityColor",A.reflectivityColor),A.microSurface!==null&&P.setFloat("glossiness",A.microSurface))):A.getClassName()==="StandardMaterial"&&(A.specularTexture!==null&&(P.setTexture("reflectivitySampler",A.specularTexture),P.setMatrix("reflectivityMatrix",A.specularTexture.getTextureMatrix())),A.specularColor!==null&&P.setColor3("reflectivityColor",A.specularColor))),Xa(P,A,this._scene),_.useBones&&_.computeBonesUsingShaders&&_.skeleton){const I=_.skeleton;if(I.isUsingTextureForMatrices&&P.getUniformIndex("boneTextureWidth")>-1){const L=I.getTransformMatrixTexture(_);P.setTexture("boneSampler",L),P.setFloat("boneTextureWidth",4*(I.bones.length+1))}else P.setMatrices("mBones",_.skeleton.getTransformMatrices(_));this._enableVelocity&&P.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[_.uniqueId])}I0(_,P),_.morphTargetManager&&_.morphTargetManager.isUsingTextureForTargets&&_.morphTargetManager._bind(P),this._enableVelocity&&(P.setMatrix("previousWorld",this._previousTransformationMatrices[y.uniqueId].world),P.setMatrix("previousViewProjection",this._previousTransformationMatrices[y.uniqueId].viewProjection)),C&&_.hasThinInstances&&P.setMatrix("world",T),_._processRendering(y,g,P,A.fillMode,b,C,(I,L)=>{I||P.setMatrix("world",L)})}this._enableVelocity&&(this._previousTransformationMatrices[y.uniqueId].world=T.clone(),this._previousTransformationMatrices[y.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),_.skeleton&&this._copyBonesTransformationMatrices(_.skeleton.getTransformMatrices(_),this._previousBonesTransformationMatrices[y.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(g,_,y)=>{if((y||_===0)&&g.subMeshes)for(let v=0;v{let x;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(v.length){for(e.setColorWrite(!1),x=0;x{throw vi("GeometryBufferRendererSceneComponent")};class R8t{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(gt.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(s){s&&s.isSupported&&(this._geometryBufferRenderer=s)},enumerable:!0,configurable:!0});gt.prototype.enableGeometryBufferRenderer=function(s=1,e=15,t){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new Nr(this,s,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};gt.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class BYe{constructor(e){this.name=ot.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ot.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}Nr._SceneComponentInitialization=s=>{let e=s._getComponent(ot.NAME_GEOMETRYBUFFERRENDERER);e||(e=new BYe(s),s._addComponent(e))};class Hx extends Ft{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,n,a,o,l=0,c=!1,u=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,n,a,o,`#define GEOMETRY_SUPPORTED #define SAMPLES 64.0 #define OBJECT_BASED`,l,void 0,null,c),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=u,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new R8t)),this._applyMode()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>_It),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>gIt),void 0)])),super._gatherImports(e,t)}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else if(this._prePassRenderer)t=this._prePassRenderer.excludedSkinnedMesh;else return;t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else if(this._prePassRenderer)t=this._prePassRenderer.excludedSkinnedMesh;else return;const i=t.indexOf(e);i!==-1&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return fe.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=he.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new we(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(Nr.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=se.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new we(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(Nr.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[i])}else if(this._prePassRenderer){const i=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[i])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join(` `))}}static _Parse(e,t,i,r){return qe.Parse(()=>new Hx(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}F([X()],Hx.prototype,"motionStrength",void 0);F([X()],Hx.prototype,"motionBlurSamples",null);F([X()],Hx.prototype,"isObjectBased",null);ve("BABYLON.MotionBlurPostProcess",Hx);const I8t="refractionPixelShader",P8t="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";de.ShadersStore[I8t]=P8t;class jx extends Ft{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,n,a,o,l,c,u){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,o,l,c,u),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=n,this.refractionTextureUrl=t,this.onActivateObservable.add(h=>{this._refTexture=this._refTexture||new xe(t,h.getScene())}),this.onApplyObservable.add(h=>{h.setColor3("baseColor",this.color),h.setFloat("depth",this.depth),h.setFloat("colorLevel",this.colorLevel),h.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return qe.Parse(()=>new jx(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}F([X()],jx.prototype,"color",void 0);F([X()],jx.prototype,"depth",void 0);F([X()],jx.prototype,"colorLevel",void 0);F([X()],jx.prototype,"refractionTextureUrl",void 0);ve("BABYLON.RefractionPostProcess",jx);const kYe="sharpenPixelShader",UYe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;de.ShadersStore[kYe]=UYe;const zYe={name:kYe,shader:UYe},w8t=Object.freeze(Object.defineProperty({__proto__:null,sharpenPixelShader:zYe},Symbol.toStringTag,{value:"Module"}));class gT extends Ft{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,n,a,o=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,n,a,null,o,void 0,null,l),this.colorAmount=1,this.edgeAmount=.3,this.onApply=c=>{c.setFloat2("screenSize",this.width,this.height),c.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>jRt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>w8t),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return qe.Parse(()=>new gT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}F([X()],gT.prototype,"colorAmount",void 0);F([X()],gT.prototype,"edgeAmount",void 0);ve("BABYLON.SharpenPostProcess",gT);class n3{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Me.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Me.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Me.MakeArray(e||this._cameras);if(!i)return;const r=[];let n;for(n=0;n0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const i=this._renderEffects[t].getPostProcesses();if(i)for(const r of i)r.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}F([X()],n3.prototype,"_name",void 0);class VYe{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(gt.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let s=this._getComponent(ot.NAME_POSTPROCESSRENDERPIPELINEMANAGER);s||(s=new GYe(this),this._addComponent(s)),this._postProcessRenderPipelineManager=new VYe}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class GYe{constructor(e){this.name=ot.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ot.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class Fl extends n3{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new Fde(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new kde(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add(()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new Fde(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new vg("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,xe.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new Yr(o,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new mT("Grain",1,null,xe.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new Yr(o,this.GrainPostProcessId,()=>this.grain,!0);let l=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,l?Me.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),l=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const t of this._cameras){const i=this._scene.enableDepthRenderer(t);i.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(t=>{this._cameras.indexOf(t.activeCamera)>-1&&(this.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const t=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=t.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new Kee("imageProcessing",1,null,xe.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new Yr(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,(!this._cameras||this._cameras.length===0)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new pT("fxaa",1,null,xe.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new Yr(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1)&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&fe.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew Fl(e._name,e._name._hdr,t),e,t,i)}}F([X()],Fl.prototype,"sharpenEnabled",null);F([X()],Fl.prototype,"bloomKernel",null);F([X()],Fl.prototype,"_bloomWeight",void 0);F([X()],Fl.prototype,"_bloomThreshold",void 0);F([X()],Fl.prototype,"_hdr",void 0);F([X()],Fl.prototype,"bloomWeight",null);F([X()],Fl.prototype,"bloomThreshold",null);F([X()],Fl.prototype,"bloomScale",null);F([X()],Fl.prototype,"bloomEnabled",null);F([X()],Fl.prototype,"depthOfFieldEnabled",null);F([X()],Fl.prototype,"depthOfFieldBlurLevel",null);F([X()],Fl.prototype,"fxaaEnabled",null);F([X()],Fl.prototype,"samples",null);F([X()],Fl.prototype,"imageProcessingEnabled",null);F([X()],Fl.prototype,"glowLayerEnabled",null);F([X()],Fl.prototype,"chromaticAberrationEnabled",null);F([X()],Fl.prototype,"grainEnabled",null);ve("BABYLON.DefaultRenderingPipeline",Fl);const WYe="chromaticAberrationPixelShader",KYe=`uniform sampler2D textureSampler; uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} float radius2=centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);vec4 r=texture2D(textureSampler,ref_coords_r);vec4 g=texture2D(textureSampler,ref_coords_g);vec4 b=texture2D(textureSampler,ref_coords_b);float a=clamp(r.a+g.a+b.a,0.,1.);gl_FragColor=vec4(r.r,g.g,b.b,a);}`;de.ShadersStore[WYe]=KYe;const HYe={name:WYe,shader:KYe},D8t=Object.freeze(Object.defineProperty({__proto__:null,chromaticAberrationPixelShader:HYe},Symbol.toStringTag,{value:"Module"})),L8t="lensHighlightsPixelShader",O8t=`uniform sampler2D textureSampler; uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } else { lum_threshold=0.5+0.44*threshold; } luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); #ifdef PENTAGON blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); #else blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); #endif blurred/=39.0;gl_FragColor=blurred;}`;de.ShadersStore[L8t]=O8t;const N8t="depthOfFieldPixelShader",F8t=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; #define PI 3.14159265 #define TWOPI 6.28318530 #define inverse_focal_length 0.1 vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) {float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} col/=total_weight; if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} return col;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); float depth=texture2D(depthSampler,distorted_coords).r; float distance=near+(far-near)*depth; vec4 color=texture2D(textureSampler,vUV); float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} `;de.ShadersStore[N8t]=F8t;class B8t extends n3{constructor(e,t,i,r=1,n){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=t.dof_gain!==void 0?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=t.dof_focus_distance!==void 0?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=t.dof_pentagon!==void 0?t.dof_pentagon:!0,this._blurNoise=t.blur_noise!==void 0?t.blur_noise:!0,this._createChromaticAberrationPostProcess(r),this._createHighlightsPostProcess(r),this._createDepthOfFieldPostProcess(r/4),this.addEffect(new Yr(i.getEngine(),this.LensChromaticAberrationEffect,()=>this._chromaticAberrationPostProcess,!0)),this.addEffect(new Yr(i.getEngine(),this.HighlightsEnhancingEffect,()=>this._highlightsPostProcess,!0)),this.addEffect(new Yr(i.getEngine(),this.LensDepthOfFieldEffect,()=>this._depthOfFieldPostProcess,!0)),this._highlightsGain===-1&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),n&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect(`#define PENTAGON `),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){this._highlightsGain===-1&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new Ft("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,xe.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=t=>{t.setFloat("chromatic_aberration",this._chromaticAberration),t.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),t.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),t.setFloat("radialIntensity",1),t.setFloat2("direction",17,17),t.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new Ft("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,xe.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?`#define PENTAGON `:""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=t=>{t.setFloat("gain",this._highlightsGain),t.setFloat("threshold",this._highlightsThreshold),t.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),t.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),t.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new Ft("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,xe.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=t=>{t.setTexture("depthSampler",this._depthTexture),t.setTexture("grainSampler",this._grainTexture),t.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),t.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),t.setFloat("grain_amount",this._grainAmount),t.setBool("blur_noise",this._blurNoise),t.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),t.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),t.setFloat("distortion",this._distortion),t.setBool("dof_enabled",this._dofDistance!==-1),t.setFloat("screen_distance",1/(.1-1/this._dofDistance)),t.setFloat("aperture",this._dofAperture),t.setFloat("darken",this._dofDarken),t.setFloat("edge_blur",this._edgeBlur),t.setBool("highlights",this._highlightsGain!==-1),this._scene.activeCamera&&(t.setFloat("near",this._scene.activeCamera.minZ),t.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const t=new Uint8Array(1048576);for(let r=0;rthis._originalColorPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t{if(!this._scene.activeCamera)return;const c=a?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,u=a?this._originalColorPostProcess.width:this._originalColorPostProcess.height;l.setFloat("outSize",c>0?c:u),l.setInt("samples",this.bilateralSamples),l.setFloat("soften",this.bilateralSoften),l.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?l.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&l.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o.autoClear=!1,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(this._bits[0]&1431655765)<<1|(this._bits[0]&2863311530)>>>1>>>0,this._bits[0]=(this._bits[0]&858993459)<<2|(this._bits[0]&3435973836)>>>2>>>0,this._bits[0]=(this._bits[0]&252645135)<<4|(this._bits[0]&4042322160)>>>4>>>0,this._bits[0]=(this._bits[0]&16711935)<<8|(this._bits[0]&4278255360)>>>8>>>0,this._bits[0]*23283064365386963e-26}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=t*2*Math.PI,r=1-e*.85,n=Math.sqrt(1-r*r);return new D(Math.cos(i)*n,Math.sin(i)*n,r)}_generateHemisphere(){const e=this.samples,t=[];let i,r=0;for(;r{n?a.push(Ue(()=>Promise.resolve().then(()=>J8t),void 0)):a.push(Ue(()=>Promise.resolve().then(()=>q8t),void 0))}),this._ssaoPostProcess.autoClear=!1,this._ssaoPostProcess.onApply=n=>{if(this._scene.activeCamera){if(n.setArray3("sampleSphere",this._sampleSphere),n.setFloat("randTextureTiles",32),n.setFloat("samplesFactor",1/this.samples),n.setFloat("totalStrength",this.totalStrength),n.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),n.setFloat("radius",this.radius),n.setFloat("maxZ",this.maxZ),n.setFloat("minZAspect",this.minZAspect),n.setFloat("base",this.base),n.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Nt.PERSPECTIVE_CAMERA)n.setMatrix3x3("depthProjection",Yo.PERSPECTIVE_DEPTH_PROJECTION),n.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),n.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const a=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,l=this._scene.activeCamera.orthoLeft??-a,c=this._scene.activeCamera.orthoRight??a,u=this._scene.activeCamera.orthoBottom??-o,h=this._scene.activeCamera.orthoTop??o;n.setMatrix3x3("depthProjection",Yo.ORTHO_DEPTH_PROJECTION),n.setFloat("xViewport",(c-l)*.5),n.setFloat("yViewport",(h-u)*.5)}n.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(n.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),n.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(n.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),n.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),n.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new k8t)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Ft("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,(i,r)=>{i?r.push(Ue(()=>Promise.resolve().then(()=>eRt),void 0)):r.push(Ue(()=>Promise.resolve().then(()=>V8t),void 0))}),this._ssaoCombinePostProcess.onApply=i=>{const r=this._scene.activeCamera.viewport;i.setVector4("viewport",se.Vector4[0].copyFromFloats(r.x,r.y,r.width,r.height)),i.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const t=new Uint8Array(65536),i=we.Zero();for(let n=0;nnew Yo(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}Yo.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];Yo.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];F([X()],Yo.prototype,"totalStrength",void 0);F([X()],Yo.prototype,"maxZ",void 0);F([X()],Yo.prototype,"minZAspect",void 0);F([X("epsilon")],Yo.prototype,"_epsilon",void 0);F([X("samples")],Yo.prototype,"_samples",void 0);F([X("textureSamples")],Yo.prototype,"_textureSamples",void 0);F([X()],Yo.prototype,"_forceGeometryBuffer",void 0);F([X()],Yo.prototype,"_ratio",void 0);F([X()],Yo.prototype,"_textureType",void 0);F([X()],Yo.prototype,"radius",void 0);F([X()],Yo.prototype,"base",void 0);F([X("bypassBlur")],Yo.prototype,"_bypassBlur",void 0);F([X("expensiveBlur")],Yo.prototype,"_expensiveBlur",void 0);F([X()],Yo.prototype,"bilateralSamples",void 0);F([X()],Yo.prototype,"bilateralSoften",void 0);F([X()],Yo.prototype,"bilateralTolerance",void 0);ve("BABYLON.SSAO2RenderingPipeline",Yo);const U8t="ssaoPixelShader",z8t=`uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSAO uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) {vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} void main() {vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Yr(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){super._attachCameras(e,t);for(const i of this._cameras)this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let t=0;t{const i=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*i}),this._blurVPostProcess.onActivateObservable.add(()=>{const i=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*i})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const i=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271],r=1/16;this._ssaoPostProcess=new Ft("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,`#define SAMPLES 16 #define SSAO`),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=n=>{this._firstUpdate&&(n.setArray3("sampleSphere",i),n.setFloat("samplesFactor",r),n.setFloat("randTextureTiles",4)),n.setFloat("totalStrength",this.totalStrength),n.setFloat("radius",this.radius),n.setFloat("area",this.area),n.setFloat("fallOff",this.fallOff),n.setFloat("base",this.base),n.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),n.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Ft("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,xe.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",se.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let r=0;r0.0) hitCoord-=dir;else hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} /** * Tests the given world position (hitCoord) according to the given reflection vector (dir) * until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). */ ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) {ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const d=this._geometryBufferRenderer,f=this._prePassRenderer;if(!f&&!d)return;if(d){const _=d.getTextureIndex(Nr.POSITION_TEXTURE_TYPE),y=d.getTextureIndex(Nr.REFLECTIVITY_TEXTURE_TYPE);h.setTexture("normalSampler",d.getGBuffer().textures[1]),h.setTexture("positionSampler",d.getGBuffer().textures[_]),h.setTexture("reflectivitySampler",d.getGBuffer().textures[y])}else if(f){const _=f.getIndex(1),y=f.getIndex(3),v=f.getIndex(6);h.setTexture("normalSampler",f.getRenderTarget().textures[v]),h.setTexture("positionSampler",f.getRenderTarget().textures[_]),h.setTexture("reflectivitySampler",f.getRenderTarget().textures[y])}const p=t.activeCamera;if(!p)return;const m=p.getViewMatrix(!0),g=p.getProjectionMatrix(!0);h.setMatrix("projection",g),h.setMatrix("view",m),h.setFloat("threshold",this.threshold),h.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),h.setFloat("strength",this.strength),h.setFloat("stepSize",this.step),h.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join(` `))}static _Parse(e,t,i,r){return qe.Parse(()=>new op(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}F([X()],op.prototype,"threshold",void 0);F([X()],op.prototype,"strength",void 0);F([X()],op.prototype,"reflectionSpecularFalloffExponent",void 0);F([X()],op.prototype,"step",void 0);F([X()],op.prototype,"roughnessFactor",void 0);F([X()],op.prototype,"enableSmoothReflections",null);F([X()],op.prototype,"reflectionSamples",null);F([X()],op.prototype,"smoothSteps",null);ve("BABYLON.ScreenSpaceReflectionPostProcess",op);const H8t="standardPixelShader",j8t=`uniform sampler2D textureSampler;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS #if defined(PASS_POST_PROCESS) void main(void) {vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} #endif #if defined(DOWN_SAMPLE_X4) uniform vec2 dsOffsets[16];void main(void) {vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} #endif #if defined(BRIGHT_PASS) uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) {vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} #endif #if defined(VLSMERGE) uniform sampler2D originalSampler;void main(void) {gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} #endif #if defined(LUMINANCE) uniform vec2 lumOffsets[4];void main() {float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) {color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); #ifdef WEIGHTED_AVERAGE float GreyValue=dot(color.rgb,weight); #endif #ifdef BRIGHTNESS float GreyValue=max(color.r,max(color.g,color.b)); #endif #ifdef HSL_COMPONENT float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); #endif #ifdef MAGNITUDE float GreyValue=length(color.rgb); #endif maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} #endif #if defined(LUMINANCE_DOWN_SAMPLE) uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; #ifdef FINAL_DOWN_SAMPLER #include #endif void main() {vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) {color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} average/=9.0; #ifdef FINAL_DOWN_SAMPLER gl_FragColor=pack(average); #else gl_FragColor=vec4(average,average,0.0,1.0); #endif } #endif #if defined(HDR) uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() {vec4 color=texture2D(textureAdderSampler,vUV); #ifndef AUTO_EXPOSURE vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; #endif gl_FragColor=color;} #endif #if defined(LENS_FLARE) #define GHOSTS 3 uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) {float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} float noise(in vec2 p) {vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), hash(i+vec2(1.0,0.0)),u.x), mix(hash(i+vec2(0.0,1.0)), hash(i+vec2(1.0,1.0)),u.x),u.y);} float fbm(vec2 p) {float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} vec3 pattern(vec2 uv) {vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} float luminance(vec3 color) {return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) {return vec4( texture2D(tex,texcoord+direction*distortion.r).r, texture2D(tex,texcoord+direction*distortion.g).g, texture2D(tex,texcoord+direction*distortion.b).b, 1.0 );} void main(void) {vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} gl_FragColor=result/float(nSamples);} #endif `;de.ShadersStore[H8t]=j8t;class ls extends n3{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join(` `))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer()){fe.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect(`#define VLS #define NB_STEPS `+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect(`#define MOTION_BLUR #define MAX_MOTION_SAMPLES `+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,n){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=n||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new op("HDRPass",t,e,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new Yr(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Ft("HDRPass","standard",[],[],e,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new Yr(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Ft("HDRDepthOfFieldSource","standard",[],[],e,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Yr(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Ft("HDRVLSFinal","standard",[],[],e,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Yr(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Ft("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Yr(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Ft("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Yr(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new pT("fxaa",1,null,xe.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new Yr(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&fe.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Ft("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=r=>{let n=0;const a=this.downSampleX4PostProcess.width,o=this.downSampleX4PostProcess.height;for(let l=-2;l<2;l++)for(let c=-2;c<2;c++)i[n]=(l+.5)*(1/a),i[n+1]=(c+.5)*(1/o),n+=2;r.setArray2("dsOffsets",i)},this.addEffect(new Yr(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Ft("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=r=>{const n=1/this.brightPassPostProcess.width,a=1/this.brightPassPostProcess.height;i[0]=-.5*n,i[1]=.5*a,i[2]=.5*n,i[3]=.5*a,i[4]=-.5*n,i[5]=-.5*a,i[6]=.5*n,i[7]=-.5*a,r.setArray2("dsOffsets",i),r.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new Yr(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){const n=e.getEngine(),a=new Ho("HDRBlurH_"+i,new we(1,0),this[r],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new Ho("HDRBlurV_"+i,new we(0,1),this[r],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);a.onActivateObservable.add(()=>{const l=a.width/n.getRenderWidth();a.kernel=this[r]*l}),o.onActivateObservable.add(()=>{const l=o.height/n.getRenderHeight();o.kernel=this.horizontalBlur?64*l:this[r]*l}),this.addEffect(new Yr(e.getEngine(),"HDRBlurH"+i,()=>a,!0)),this.addEffect(new Yr(e.getEngine(),"HDRBlurV"+i,()=>o,!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Ft("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=i=>{i.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),i.setTexture("lensSampler",this.lensTexture),i.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new Yr(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const r=i.getGBuffer();this.volumetricLightPostProcess=new Ft("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS #define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const n=we.Zero();this.volumetricLightPostProcess.onApply=a=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const o=this.sourceLight.getShadowGenerator();a.setTexture("shadowMapSampler",o.getShadowMap()),a.setTexture("positionSampler",r.textures[2]),a.setColor3("sunColor",this.sourceLight.diffuse),a.setVector3("sunDirection",this.sourceLight.getShadowDirection()),a.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),a.setMatrix("shadowViewProjection",o.getTransformMatrix()),a.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),a.setFloat("scatteringPower",this.volumetricLightPower),n.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),n.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),a.setVector2("depthValues",n)}},this.addEffect(new Yr(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Ft("HDRVLSMerge","standard",[],["originalSampler"],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=a=>{a.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new Yr(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,ls.LuminanceSteps);this.luminancePostProcess=new Ft("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const r=[];this.luminancePostProcess.onApply=a=>{const o=1/this.luminancePostProcess.width,l=1/this.luminancePostProcess.height;r[0]=-.5*o,r[1]=.5*l,r[2]=.5*o,r[3]=.5*l,r[4]=-.5*o,r[5]=-.5*l,r[6]=.5*o,r[7]=-.5*l,a.setArray2("lumOffsets",r)},this.addEffect(new Yr(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let a=ls.LuminanceSteps-1;a>=0;a--){i=Math.pow(3,a);let o=`#define LUMINANCE_DOWN_SAMPLE `;a===0&&(o+="#define FINAL_DOWN_SAMPLER");const l=new Ft("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,t);this.luminanceDownSamplePostProcesses.push(l)}let n=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((a,o)=>{const l=new Array(18);a.onApply=c=>{if(!n)return;let u=0;for(let h=-1;h<2;h++)for(let d=-1;d<2;d++)l[u]=h/n.width,l[u+1]=d/n.height,u+=2;c.setArray2("dsOffsets",l),c.setFloat("halfDestPixelSize",.5/n.width),o===this.luminanceDownSamplePostProcesses.length-1?n=this.luminancePostProcess:n=a},o===this.luminanceDownSamplePostProcesses.length-1&&(a.onAfterRender=()=>{const c=e.getEngine().readPixels(0,0,1,1),u=new mt(1/(255*255*255),1/(255*255),1/255,1);c.then(h=>{const d=new Uint8Array(h.buffer);this._hdrCurrentLuminance=(d[0]*u.x+d[1]*u.y+d[2]*u.z+d[3]*u.w)/100})}),this.addEffect(new Yr(e.getEngine(),"HDRLuminanceDownSample"+o,()=>a,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Ft("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(` `),0);let r=1,n=0,a=0;this.hdrPostProcess.onApply=o=>{if(o.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),n+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{const l=(a-n)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*l?r-=this.hdrIncreaseRate*l:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=At.Clamp(r,this.hdrMinimumLuminance,1e20),o.setFloat("averageLuminance",r)),a=n,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new Yr(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Ft("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new Yr(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Ft("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new Yr(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new we(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=a=>{a.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),a.setTexture("lensColorSampler",this.lensColorTexture),a.setFloat("strength",this.lensFlareStrength),a.setFloat("ghostDispersal",this.lensFlareGhostDispersal),a.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,a.setVector2("resolution",i),a.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const r=he.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),n=he.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=a=>{if(!this._scene.activeCamera)return;a.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),a.setTexture("lensDirtSampler",this.lensFlareDirtTexture),a.setTexture("lensStarSampler",this.lensStarTexture);const o=this._scene.activeCamera.getViewMatrix().getRow(0),l=this._scene.activeCamera.getViewMatrix().getRow(2);let c=D.Dot(o.toVector3(),new D(1,0,0))+D.Dot(l.toVector3(),new D(0,0,1));c*=4;const u=he.FromValues(Math.cos(c)*.5,-Math.sin(c),0,0,Math.sin(c),Math.cos(c)*.5,0,0,0,0,1,0,0,0,0,1),h=n.multiply(u).multiply(r);a.setMatrix("lensStarMatrix",h),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Ft("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=i=>{i.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),i.setTexture("depthSampler",this._getDepthTexture()),i.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new Yr(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new Hx("HDRMotionBlur",e,t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Ft("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,xe.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR #define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,r=he.Identity();const n=he.Identity();let a=he.Identity();const o=we.Zero();this.motionBlurPostProcess.onApply=l=>{a=e.getProjectionMatrix().multiply(e.getViewMatrix()),a.invertToRef(n),l.setMatrix("inverseViewProjection",n),l.setMatrix("prevViewProjection",r),r=a,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,l.setVector2("screenSize",o),i=e.getEngine().getFps()/60,l.setFloat("motionScale",i),l.setFloat("motionStrength",this.motionStrength),l.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new Yr(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew ls(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&qe.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}}ls.LuminanceSteps=6;F([X()],ls.prototype,"brightThreshold",void 0);F([X()],ls.prototype,"blurWidth",void 0);F([X()],ls.prototype,"horizontalBlur",void 0);F([X()],ls.prototype,"exposure",null);F([ii("lensTexture")],ls.prototype,"lensTexture",void 0);F([X()],ls.prototype,"volumetricLightCoefficient",void 0);F([X()],ls.prototype,"volumetricLightPower",void 0);F([X()],ls.prototype,"volumetricLightBlurScale",void 0);F([X()],ls.prototype,"hdrMinimumLuminance",void 0);F([X()],ls.prototype,"hdrDecreaseRate",void 0);F([X()],ls.prototype,"hdrIncreaseRate",void 0);F([X()],ls.prototype,"hdrAutoExposure",null);F([ii("lensColorTexture")],ls.prototype,"lensColorTexture",void 0);F([X()],ls.prototype,"lensFlareStrength",void 0);F([X()],ls.prototype,"lensFlareGhostDispersal",void 0);F([X()],ls.prototype,"lensFlareHaloWidth",void 0);F([X()],ls.prototype,"lensFlareDistortionStrength",void 0);F([X()],ls.prototype,"lensFlareBlurWidth",void 0);F([ii("lensStarTexture")],ls.prototype,"lensStarTexture",void 0);F([ii("lensFlareDirtTexture")],ls.prototype,"lensFlareDirtTexture",void 0);F([X()],ls.prototype,"depthOfFieldDistance",void 0);F([X()],ls.prototype,"depthOfFieldBlurWidth",void 0);F([X()],ls.prototype,"motionStrength",null);F([X()],ls.prototype,"objectBasedMotionBlur",null);F([X()],ls.prototype,"_ratio",void 0);F([X()],ls.prototype,"BloomEnabled",null);F([X()],ls.prototype,"DepthOfFieldEnabled",null);F([X()],ls.prototype,"LensFlareEnabled",null);F([X()],ls.prototype,"HDREnabled",null);F([X()],ls.prototype,"VLSEnabled",null);F([X()],ls.prototype,"MotionBlurEnabled",null);F([X()],ls.prototype,"fxaaEnabled",null);F([X()],ls.prototype,"screenSpaceReflectionsEnabled",null);F([X()],ls.prototype,"volumetricLightStepsCount",null);F([X()],ls.prototype,"motionBlurSamples",null);F([X()],ls.prototype,"samples",null);ve("BABYLON.StandardRenderingPipeline",ls);class X8t{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const Y8t=he.Compose(new D(.5,.5,.5),Pe.Identity(),new D(.5,.5,.5)),Q8t=he.Compose(new D(.5,.5,1),Pe.Identity(),new D(.5,.5,0));class on extends n3{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(e===0&&this._reflectivityThreshold!==0||e!==0&&this._reflectivityThreshold===0?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=e===0&&this._blurDispersionStrength!==0||e!==0&&this._blurDispersionStrength===0;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,n=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=n,this._forceGeometryBuffer=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const a=t.enableGeometryBufferRenderer();a&&(a.enableReflectivity=!0,a.useSpecificClearForDepthTexture=!0)}else{const a=t.enablePrePassRenderer();a&&(a.useSpecificClearForDepthTexture=!0,a.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var r,n;const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&((r=this._scene.activeCamera)==null?void 0:r._getFirstPostProcess())===this._ssrPostProcess){const a=t.getRenderTarget();a&&a.textures&&(i=a.textures[t.getIndex(4)].getSize())}else(n=this._ssrPostProcess)!=null&&n.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){var i,r,n,a,o;const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),this._reflectivityThreshold===0&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(((i=this._geometryBufferRenderer)==null?void 0:i.generateNormalsInWorldSpace)??((r=this._prePassRenderer)==null?void 0:r.generateNormalsInWorldSpace))&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(n=this._geometryBufferRenderer)!=null&&n.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=(a=this._cameras)==null?void 0:a[0];t&&t.mode===1&&e.push("#define ORTHOGRAPHIC_CAMERA"),(o=this._ssrPostProcess)==null||o.updateEffect(e.join(` `))}_buildPipeline(){var t;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const i=(t=this._cameras)==null?void 0:t[0];i&&(this._depthRendererCamera=i,this._depthRenderer=new u_(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),i.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new Yr(e,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new Yr(e,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new Yr(e,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;e!==-1&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,r;for(let n=0;n{e?t.push(Ue(()=>Promise.resolve().then(()=>oRt),void 0)):t.push(Ue(()=>Promise.resolve().then(()=>rRt),void 0))}),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const l=t.getTextureIndex(Nr.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[l]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const l=i.getIndex(5),c=i.getIndex(3),u=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[u]),e.setTexture("depthSampler",i.getRenderTarget().textures[l]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[c])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const r=this._scene.activeCamera;if(!r)return;const n=r.getViewMatrix(),a=r.getProjectionMatrix();a.invertToRef(se.Matrix[0]),n.invertToRef(se.Matrix[1]),e.setMatrix("projection",a),e.setMatrix("view",n),e.setMatrix("invView",se.Matrix[1]),e.setMatrix("invProjectionMatrix",se.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();he.ScalingToRef(o.width,o.height,1,se.Matrix[2]),a.multiplyToRef(this._scene.getEngine().isWebGPU?Q8t:Y8t,se.Matrix[3]),se.Matrix[3].multiplyToRef(se.Matrix[2],se.Matrix[4]),e.setMatrix("projectionPixel",se.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new X8t)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Ft("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,(n,a)=>{n?a.push(Ue(()=>Promise.resolve().then(()=>xMe),void 0)):a.push(Ue(()=>Promise.resolve().then(()=>yMe),void 0))}),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(n=>{var o;const a=((o=this._blurPostProcessX)==null?void 0:o.inputTexture.width)??this._scene.getEngine().getRenderWidth();n.setFloat2("texelOffsetScale",this._blurDispersionStrength/a,0)}),this._blurPostProcessY=new Ft("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,(n,a)=>{n?a.push(Ue(()=>Promise.resolve().then(()=>xMe),void 0)):a.push(Ue(()=>Promise.resolve().then(()=>yMe),void 0))}),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(n=>{var o;const a=((o=this._blurPostProcessY)==null?void 0:o.inputTexture.height)??this._scene.getEngine().getRenderHeight();n.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/a)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let r="";this._debug&&(r+=`#define SSRAYTRACE_DEBUG `),this._inputTextureColorIsInGammaSpace&&(r+=`#define SSR_INPUT_IS_GAMMA_SPACE `),this._generateOutputInGammaSpace&&(r+=`#define SSR_OUTPUT_IS_GAMMA_SPACE `),this.useFresnel&&(r+=`#define SSR_BLEND_WITH_FRESNEL `,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Ft("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,(n,a)=>{n?a.push(Ue(()=>Promise.resolve().then(()=>lRt),void 0)):a.push(Ue(()=>Promise.resolve().then(()=>sRt),void 0))}),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(n=>{var l;const a=this._geometryBufferRenderer,o=this._prePassRenderer;if(!(!o&&!a)){if(o&&((l=this._scene.activeCamera)==null?void 0:l._getFirstPostProcess())===this._ssrPostProcess){const c=o.getRenderTarget();c&&c.textures&&n.setTexture("mainSampler",c.textures[o.getIndex(4)])}else n.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(a){const c=a.getTextureIndex(Nr.REFLECTIVITY_TEXTURE_TYPE);n.setTexture("reflectivitySampler",a.getGBuffer().textures[c]),this.useFresnel&&(n.setTexture("normalSampler",a.getGBuffer().textures[1]),n.setTexture("depthSampler",a.getGBuffer().textures[0]))}else if(o){const c=o.getIndex(3);if(n.setTexture("reflectivitySampler",o.getRenderTarget().textures[c]),this.useFresnel){const u=o.getIndex(5),h=o.getIndex(6);n.setTexture("normalSampler",o.getRenderTarget().textures[h]),n.setTexture("depthSampler",o.getRenderTarget().textures[u])}}if(n.setFloat("strength",this.strength),n.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),n.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const c=this._scene.activeCamera;if(c){const u=c.getProjectionMatrix();u.invertToRef(se.Matrix[0]),n.setMatrix("projection",u),n.setMatrix("invProjectionMatrix",se.Matrix[0])}}}})}serialize(){const e=qe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return qe.Parse(()=>new on(e._name,t,e._ratio),e,t,i)}}F([X()],on.prototype,"samples",null);F([X()],on.prototype,"maxDistance",void 0);F([X()],on.prototype,"step",void 0);F([X()],on.prototype,"thickness",void 0);F([X()],on.prototype,"strength",void 0);F([X()],on.prototype,"reflectionSpecularFalloffExponent",void 0);F([X()],on.prototype,"maxSteps",void 0);F([X()],on.prototype,"roughnessFactor",void 0);F([X()],on.prototype,"selfCollisionNumSkip",void 0);F([X()],on.prototype,"_reflectivityThreshold",void 0);F([X("_ssrDownsample")],on.prototype,"_ssrDownsample",void 0);F([X()],on.prototype,"ssrDownsample",null);F([X("blurDispersionStrength")],on.prototype,"_blurDispersionStrength",void 0);F([X("blurDownsample")],on.prototype,"_blurDownsample",void 0);F([X("enableSmoothReflections")],on.prototype,"_enableSmoothReflections",void 0);F([X("environmentTexture")],on.prototype,"_environmentTexture",void 0);F([X("environmentTextureIsProbe")],on.prototype,"_environmentTextureIsProbe",void 0);F([X("attenuateScreenBorders")],on.prototype,"_attenuateScreenBorders",void 0);F([X("attenuateIntersectionDistance")],on.prototype,"_attenuateIntersectionDistance",void 0);F([X("attenuateIntersectionIterations")],on.prototype,"_attenuateIntersectionIterations",void 0);F([X("attenuateFacingCamera")],on.prototype,"_attenuateFacingCamera",void 0);F([X("attenuateBackfaceReflection")],on.prototype,"_attenuateBackfaceReflection",void 0);F([X("clipToFrustum")],on.prototype,"_clipToFrustum",void 0);F([X("useFresnel")],on.prototype,"_useFresnel",void 0);F([X("enableAutomaticThicknessComputation")],on.prototype,"_enableAutomaticThicknessComputation",void 0);F([X("backfaceDepthTextureDownsample")],on.prototype,"_backfaceDepthTextureDownsample",void 0);F([X("backfaceForceDepthWriteTransparentMeshes")],on.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);F([X("isEnabled")],on.prototype,"_isEnabled",void 0);F([X("inputTextureColorIsInGammaSpace")],on.prototype,"_inputTextureColorIsInGammaSpace",void 0);F([X("generateOutputInGammaSpace")],on.prototype,"_generateOutputInGammaSpace",void 0);F([X("debug")],on.prototype,"_debug",void 0);ve("BABYLON.SSRRenderingPipeline",on);const $8t="taaPixelShader",Z8t=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);} `;de.ShadersStore[$8t]=Z8t;class a3 extends n3{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():this._cameras!==null&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,r=0){const n=t.getEngine();super(n,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._hs=new fje(this.samples),this.isSupported&&(this._createPingPongTextures(n.getRenderWidth(),n.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){var r,n;const i=this._scene.getEngine();(r=this._ping)==null||r.dispose(),(n=this._pong)==null||n.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){var t;const e=[];(t=this._taaPostProcess)==null||t.updateEffect(e.join(` `))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new Yr(e,this.TAARenderEffect,()=>this._taaPostProcess,!0)),this._createPassPostProcess(),this.addEffect(new Yr(e,this.TAAPassEffect,()=>this._passPostProcess,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){var e,t;for(let i=0;i{var t,i;const e=this._scene.activeCamera;if(((t=this._taaPostProcess)==null?void 0:t.width)!==this._ping.width||((i=this._taaPostProcess)==null?void 0:i.height)!==this._ping.height){const r=this._scene.getEngine();this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===Nt.PERSPECTIVE_CAMERA){const r=e.getProjectionMatrix();r.setRowFromFloats(2,this._hs.x,this._hs.y,r.m[10],r.m[11])}else{const r=e.getProjectionMatrix(!0);r.setRowFromFloats(3,this._hs.x+r.m[12],this._hs.y+r.m[13],r.m[14],r.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=this._pingpong^1,this._hs.next()}),this._taaPostProcess.onApplyObservable.add(e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t!=null&&t.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1})}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new D0("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=qe.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return qe.Parse(()=>new a3(e._name,t,e._ratio),e,t,i)}}F([X("samples")],a3.prototype,"_samples",void 0);F([X("msaaSamples")],a3.prototype,"_msaaSamples",void 0);F([X()],a3.prototype,"factor",void 0);F([X()],a3.prototype,"disableOnCameraMove",void 0);F([X("isEnabled")],a3.prototype,"_isEnabled",void 0);ve("BABYLON.TAARenderingPipeline",a3);const QYe="ssao2PixelShader",$Ye=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSAO float scales[16]=float[16]( 0.1, 0.11406250000000001, 0.131640625, 0.15625, 0.187890625, 0.2265625, 0.272265625, 0.325, 0.384765625, 0.4515625, 0.525390625, 0.60625, 0.694140625, 0.7890625, 0.891015625, 1.0 );uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() {vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} #endif #ifdef BLUR uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; #ifndef BLUR_BYPASS uniform sampler2D depthSampler; #ifdef BLUR_LEGACY #define inline float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} #endif #endif void main() {float result=0.0; #ifdef BLUR_BYPASS result=textureLod(textureSampler,vUV,0.0).r; #else #ifdef BLUR_H vec2 step=vec2(1.0/outSize,0.0); #else vec2 step=vec2(0.0,1.0/outSize); #endif #ifdef BLUR_LEGACY result=blur13Bilateral(textureSampler,vUV,step); #else float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i; #ifdef SSAO const scales: array=array( 0.1, 0.11406250000000001, 0.131640625, 0.15625, 0.187890625, 0.2265625, 0.272265625, 0.325, 0.384765625, 0.4515625, 0.525390625, 0.60625, 0.694140625, 0.7890625, 0.891015625, 1.0 );uniform near: f32;uniform radius: f32;var depthSamplerSampler: sampler;var depthSampler: texture_2d;var randomSamplerSampler: sampler;var randomSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;uniform randTextureTiles: f32;uniform samplesFactor: f32;uniform sampleSphere: array;uniform totalStrength: f32;uniform base: f32;uniform xViewport: f32;uniform yViewport: f32;uniform depthProjection: mat3x3f;uniform maxZ: f32;uniform minZAspect: f32;uniform texelSize: vec2f;uniform projection: mat4x4f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {var random: vec3f=textureSampleLevel(randomSampler,randomSamplerSampler,input.vUV*uniforms.randTextureTiles,0.0).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;var depthSign: f32=sign(depth);depth=depth*depthSign;var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.0).rgb;var occlusion: f32=0.0;var correctedRadius: f32=min(uniforms.radius,uniforms.minZAspect*depth/uniforms.near);var vViewRay: vec3f= vec3f((input.vUV.x*2.0-1.0)*uniforms.xViewport,(input.vUV.y*2.0-1.0)*uniforms.yViewport,depthSign);var vDepthFactor: vec3f=uniforms.depthProjection* vec3f(1.0,1.0,depth);var origin: vec3f=vViewRay*vDepthFactor;var rvec: vec3f=random*2.0-1.0;rvec.z=0.0;var dotProduct: f32=dot(rvec,normal);rvec=select( vec3f(-rvec.y,0.0,rvec.x),rvec,1.0-abs(dotProduct)>1e-2);var tangent: vec3f=normalize(rvec-normal*dot(rvec,normal));var bitangent: vec3f=cross(normal,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,normal);var difference: f32;for (var i: i32=0; i1.0 || offset.y>1.0) {continue;} var sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;var rangeCheck: f32=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} occlusion=occlusion*(1.0-smoothstep(uniforms.maxZ*0.75,uniforms.maxZ,depth));var ao: f32=1.0-uniforms.totalStrength*occlusion*uniforms.samplesFactor;var result: f32=clamp(ao+uniforms.base,0.0,1.0);fragmentOutputs.color= vec4f( vec3f(result),1.0);} #else #ifdef BLUR uniform outSize: f32;uniform soften: f32;uniform tolerance: f32;uniform samples: i32; #ifndef BLUR_BYPASS var depthSamplerSampler: sampler;var depthSampler: texture_2d; #ifdef BLUR_LEGACY fn blur13Bilateral(image: texture_2d,imageSampler: sampler,uv: vec2f,step: vec2f)->f32 {var result: f32=0.0;var off1: vec2f= vec2f(1.411764705882353)*step;var off2: vec2f= vec2f(3.2941176470588234)*step;var off3: vec2f= vec2f(5.176470588235294)*step;var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv,0.0).r);var sampleDepth: f32;var weight: f32;var weightSum: f32=30.0;result+=textureSampleLevel(image,imageSampler,uv,0.0).r*30.0;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv+off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv-off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off3,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off3,0.0).r*weight;return result/weightSum;} #endif #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs {var result: f32=0.0; #ifdef BLUR_BYPASS result=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0).r; #else #ifdef BLUR_H var step: vec2f= vec2f(1.0/uniforms.outSize,0.0); #else var step: vec2f= vec2f(0.0,1.0/uniforms.outSize); #endif #ifdef BLUR_LEGACY result=blur13Bilateral(textureSampler,textureSamplerSampler,input.vUV,step); #else var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r);var weightSum: f32=0.0;for (var i: i32=-uniforms.samples; i;var originalColorSampler: sampler;var originalColor: texture_2d;uniform viewport: vec4f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var ssaoColor: vec4f=textureSample(textureSampler,textureSamplerSampler,uniforms.viewport.xy+input.vUV*uniforms.viewport.zw);var sceneColor: vec4f=textureSample(originalColor,originalColorSampler,input.vUV);fragmentOutputs.color=sceneColor*ssaoColor; #define CUSTOM_FRAGMENT_MAIN_END } `;de.ShadersStoreWGSL[tQe]=iQe;const rQe={name:tQe,shader:iQe},eRt=Object.freeze(Object.defineProperty({__proto__:null,ssaoCombinePixelShaderWGSL:rQe},Symbol.toStringTag,{value:"Module"})),tRt="screenSpaceRayTrace",iRt=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } /** param csOrigin Camera-space ray origin,which must be within the view volume and must have z>0.01 and project within the valid screen rectangle param csDirection Unit length camera-space ray direction param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates (**not** [-1,+1] normalized device coordinates). param csZBuffer The camera-space Z buffer param csZBufferSize Dimensions of csZBuffer param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value for clipping rays headed towards the camera param stride Step in horizontal or vertical pixels between samples. This is a float because integer math is slow on GPUs,but should be set to an integer>=1 param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units to conceal banding artifacts,plus the stride ray offset. param maxSteps Maximum number of iterations. Higher gives better images but may be slow param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. 1 is a reasonable value,depending on the scene you may need to set this value to 2 param hitPixel Pixel coordinates of the first intersection with the scene param numIterations number of iterations performed param csHitPoint Camera space location of the ray hit */ #define inline bool traceScreenSpaceRay1( vec3 csOrigin, vec3 csDirection, mat4 projectToPixelMatrix, sampler2D csZBuffer, vec2 csZBufferSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER sampler2D csZBackBuffer, float csZBackSizeFactor, #endif float csZThickness, float nearPlaneZ, float stride, float jitterFraction, float maxSteps, float maxRayTraceDistance, float selfCollisionNumSkip, out vec2 startPixel, out vec2 hitPixel, out vec3 csHitPoint, out float numIterations #ifdef SSRAYTRACE_DEBUG ,out vec3 debugColor #endif ) { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; #else float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); #endif P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); #else hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); #endif #else #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); #else hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); #endif #endif } pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} #ifdef SSRAYTRACE_ENABLE_REFINEMENT if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || (refinementStepCount<=stride*1.4) && (rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} #endif return hit;} /** texCoord: in the [0,1] range depth: depth in view space (range [znear,zfar]]) */ vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef ORTHOGRAPHIC_CAMERA ndc.z=-projection[2].z*depth+projection[3].z; #else ndc.z=-projection[2].z-projection[3].z/depth; #endif #else #ifdef ORTHOGRAPHIC_CAMERA ndc.z=projection[2].z*depth+projection[3].z; #else ndc.z=projection[2].z+projection[3].z/depth; #endif #endif ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} `;de.IncludesShadersStore[tRt]=iRt;const sQe="screenSpaceReflection2PixelShader",nQe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSR_SUPPORTED uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER uniform sampler2D backDepthSampler;uniform float backSizeFactor; #endif #ifdef SSR_USE_ENVIRONMENT_CUBE uniform samplerCube envCubeSampler; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; #include #include #include vec3 hash(vec3 a) {a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; #ifdef SSR_ATTENUATE_SCREEN_BORDERS vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS attenuation*=1.0-(numIterations/maxSteps); #endif #ifdef SSR_ATTENUATE_BACKFACE_REFLECTION vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; #endif return attenuation;} #endif void main() { #ifdef SSR_SUPPORTED vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { #ifdef SSR_USE_BLUR gl_FragColor=vec4(0.); #else gl_FragColor=colorFull; #endif return;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpace(color); #endif vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(view*vec4(csNormal,0.0)).xyz; #endif float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix); #ifdef ORTHOGRAPHIC_CAMERA vec3 csViewDirection=vec3(0.,0.,1.); #else vec3 csViewDirection=normalize(csPosition); #endif vec3 csReflectedVector=reflect(csViewDirection,csNormal); #ifdef SSR_USE_ENVIRONMENT_CUBE vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); #endif #ifdef SSR_INVERTCUBICMAP wReflectedVector.y*=-1.0; #endif #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE wReflectedVector.z*=-1.0; #endif vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; #ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE envColor=toLinearSpace(envColor); #endif #else vec3 envColor=color; #endif float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; #ifdef SSRAYTRACE_DEBUG vec3 debugColor; #endif #ifdef SSR_ATTENUATE_FACING_CAMERA reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); #endif if (reflectionAttenuation>0.0) { #ifdef SSR_USE_BLUR vec3 jitt=vec3(0.); #else float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; #endif vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); rayHasHit=traceScreenSpaceRay1( csPosition, normalize(csReflectedVector+jitt), projectionPixel, depthSampler, texSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER backDepthSampler, backSizeFactor, #endif thickness, nearPlaneZ, stepSize, jitter, maxSteps, maxDistance, selfCollisionNumSkip, startPixel, hitPixel, hitPoint, numIterations #ifdef SSRAYTRACE_DEBUG ,debugColor #endif );} #ifdef SSRAYTRACE_DEBUG gl_FragColor=vec4(debugColor,1.);return; #endif vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; #ifdef SSR_INPUT_IS_GAMMA_SPACE reflectedColor=toLinearSpace(reflectedColor); #endif reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} #ifndef SSR_BLEND_WITH_FRESNEL SSR*=fresnel; #endif #ifdef SSR_USE_BLUR float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} gl_FragColor=vec4(SSR,blur_radius/255.0); #else #ifdef SSR_BLEND_WITH_FRESNEL vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #else vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #endif vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpace(finalColor); #endif gl_FragColor=vec4(finalColor,colorFull.a); #endif #else gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); #endif } `;de.ShadersStore[sQe]=nQe;const aQe={name:sQe,shader:nQe},rRt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2PixelShader:aQe},Symbol.toStringTag,{value:"Module"})),oQe="screenSpaceReflection2BlurPixelShader",lQe=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) {vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} void main() {vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} float blurRadius=colorFull.a*255.0; vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} `;de.ShadersStore[oQe]=lQe;const cQe={name:oQe,shader:lQe},yMe=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurPixelShader:cQe},Symbol.toStringTag,{value:"Module"})),uQe="screenSpaceReflection2BlurCombinerPixelShader",hQe=`uniform sampler2D textureSampler; uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; #include #ifdef SSR_BLEND_WITH_FRESNEL #include #include uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; #endif void main() { #ifdef SSRAYTRACE_DEBUG gl_FragColor=texture2D(textureSampler,vUV); #else vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpace(color); #endif #ifdef SSR_BLEND_WITH_FRESNEL vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #else vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #endif vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpace(finalColor); #endif gl_FragColor=vec4(finalColor,color.a); #endif } `;de.ShadersStore[uQe]=hQe;const dQe={name:uQe,shader:hQe},sRt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurCombinerPixelShader:dQe},Symbol.toStringTag,{value:"Module"})),nRt="screenSpaceRayTrace",aRt=`fn distanceSquared(a: vec2f,b: vec2f)->f32 { var temp=a-b; return dot(temp,temp); } /** param csOrigin Camera-space ray origin,which must be within the view volume and must have z>0.01 and project within the valid screen rectangle param csDirection Unit length camera-space ray direction param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates (**not** [-1,+1] normalized device coordinates). param csZBuffer The camera-space Z buffer param csZBufferSize Dimensions of csZBuffer param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value for clipping rays headed towards the camera param stride Step in horizontal or vertical pixels between samples. This is a var because: f32 integer math is slow on GPUs,but should be set to an integer>=1 param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units to conceal banding artifacts,plus the stride ray offset. param maxSteps Maximum number of iterations. Higher gives better images but may be slow param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss param selfCollisionNumSkip Number of steps to skip at start when raytracing to avar self: voidnull collisions. 1 is a reasonable value,depending on the scene you may need to set this value to 2 param hitPixel Pixel coordinates of the first intersection with the scene param numIterations number of iterations performed param csHitPovar Camera: i32 space location of the ray hit */ fn traceScreenSpaceRay1( csOrigin: vec3f, csDirection: vec3f, projectToPixelMatrix: mat4x4f, csZBuffer: texture_2d, csZBufferSize: vec2f, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER csZBackBuffer: texture_2d, csZBackSizeFactor: f32, #endif csZThickness: f32, nearPlaneZ: f32, stride: f32, jitterFraction: f32, maxSteps: f32, maxRayTraceDistance: f32, selfCollisionNumSkip: f32, startPixel: ptr, hitPixel: ptr, csHitPoint: ptr, numIterations: ptr #ifdef SSRAYTRACE_DEBUG ,debugColor: ptr #endif )->bool { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE var rayLength: f32=select(maxRayTraceDistance,(-nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ); #else var rayLength: f32=select(maxRayTraceDistance,(nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax)))/(P1.y-P0.y);} if ((P1.x>xMax) || (P1.xxMax)))/(P1.x-P0.x));} P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); #endif P1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)rayZMax) { var t: f32=rayZMin; rayZMin=rayZMax; rayZMax=t;} sceneZMax=textureLoad(csZBuffer,vec2(*hitPixel),0).r; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); #else hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); #endif #else #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); #else hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); #endif #endif stepCount+=1.0;} pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} #ifdef SSRAYTRACE_ENABLE_REFINEMENT if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;var invStride: f32=1.0/stride;dPQK*=invStride;var refinementStepCount: f32=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || ((refinementStepCount<=stride*1.4) && (rayZMax(*hitPixel),0).r;refinementStepCount+=1.0;} pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} #endif Q0=vec3f(Q0.xy+dQ.xy*stepCount,pqk.z);*csHitPoint=Q0/pqk.w;*numIterations=stepCount+1.0; #ifdef SSRAYTRACE_DEBUG if (((pqk.x+dPQK.x)*stepDirection)>end) {*debugColor= vec3f(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {*debugColor= vec3f(1,0,0);} else if (sceneZMax==0.0) {*debugColor= vec3f(1,1,0);} else {*debugColor= vec3f(0,stepCount/maxSteps,0);} #endif return hit;} /** texCoord: in the [0,1] range depth: depth in view space (range [znear,zfar]]) */ fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32,projection: mat4x4f,invProjectionMatrix: mat4x4f)->vec3f {var xy=texCoord*2.0-1.0;var z: f32; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef ORTHOGRAPHIC_CAMERA z=-projection[2].z*depth+projection[3].z; #else z=-projection[2].z-projection[3].z/depth; #endif #else #ifdef ORTHOGRAPHIC_CAMERA z=projection[2].z*depth+projection[3].z; #else z=projection[2].z+projection[3].z/depth; #endif #endif var w=1.0;var ndc=vec4f(xy,z,w);var eyePos: vec4f=invProjectionMatrix*ndc;var result=eyePos.xyz/eyePos.w;return result;} `;de.IncludesShadersStoreWGSL[nRt]=aRt;const fQe="screenSpaceReflection2PixelShader",pQe=`var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f; #ifdef SSR_SUPPORTED var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;var normalSampler: texture_2d;var depthSampler: texture_2d; #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER var backDepthSampler: texture_2d;uniform backSizeFactor: f32; #endif #ifdef SSR_USE_ENVIRONMENT_CUBE var envCubeSamplerSampler: sampler;var envCubeSampler: texture_cube; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f; #endif #endif uniform view: mat4x4f;uniform invView: mat4x4f;uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform projectionPixel: mat4x4f;uniform nearPlaneZ: f32;uniform stepSize: f32;uniform maxSteps: f32;uniform strength: f32;uniform thickness: f32;uniform roughnessFactor: f32;uniform reflectionSpecularFalloffExponent: f32;uniform maxDistance: f32;uniform selfCollisionNumSkip: f32;uniform reflectivityThreshold: f32; #include #include #include fn hash(a: vec3f)->vec3f {var result=fract(a*0.8);result+=dot(result,result.yxz+19.19);return fract((result.xxy+result.yxx)*result.zyx);} fn computeAttenuationForIntersection(ihitPixel: vec2f,hitUV: vec2f,vsRayOrigin: vec3f,vsHitPoint: vec3f,reflectionVector: vec3f,maxRayDistance: f32,numIterations: f32)->f32 {var attenuation: f32=1.0; #ifdef SSR_ATTENUATE_SCREEN_BORDERS var dCoords: vec2f=smoothstep(vec2f(0.2),vec2f(0.6),abs( vec2f(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE #endif #ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS attenuation*=1.0-(numIterations/uniforms.maxSteps); #endif #ifdef SSR_ATTENUATE_BACKFACE_REFLECTION var reflectionNormal: vec3f=texelFetch(normalSampler,hitPixel,0).xyz;var directionBasedAttenuation: f32=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; #endif return attenuation;} #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #ifdef SSR_SUPPORTED var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var color: vec3f=colorFull.rgb;var reflectivity: vec4f=textureSampleLevel(reflectivitySampler,reflectivitySamplerSampler,input.vUV,0.0); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) { #ifdef SSR_USE_BLUR fragmentOutputs.color= vec4f(0.); #else fragmentOutputs.color=colorFull; #endif return fragmentOutputs;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpaceVec3(color); #endif var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(uniforms.view* vec4f(csNormal,0.0)).xyz; #endif var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r;var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix); #ifdef ORTHOGRAPHIC_CAMERA var csViewDirection: vec3f= vec3f(0.,0.,1.); #else var csViewDirection: vec3f=normalize(csPosition); #endif var csReflectedVector: vec3f=reflect(csViewDirection,csNormal); #ifdef SSR_USE_ENVIRONMENT_CUBE var wReflectedVector: vec3f=(uniforms.invView* vec4f(csReflectedVector,0.0)).xyz; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC var worldPos: vec4f=uniforms.invView* vec4f(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),uniforms.vReflectionSize,uniforms.vReflectionPosition); #endif #ifdef SSR_INVERTCUBICMAP wReflectedVector.y*=-1.0; #endif #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE wReflectedVector.z*=-1.0; #endif var envColor: vec3f=textureSampleLevel(envCubeSampler,envCubeSamplerSampler,wReflectedVector,0.0).xyz; #ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE envColor=toLinearSpaceVec3(envColor); #endif #else var envColor: vec3f=color; #endif var reflectionAttenuation: f32=1.0;var rayHasHit: bool=false;var startPixel: vec2f;var hitPixel: vec2f;var hitPoint: vec3f;var numIterations: f32; #ifdef SSRAYTRACE_DEBUG var debugColor: vec3f; #endif #ifdef SSR_ATTENUATE_FACING_CAMERA reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); #endif if (reflectionAttenuation>0.0) { #ifdef SSR_USE_BLUR var jitt: vec3f= vec3f(0.); #else var roughness: f32=1.0-reflectivity.a;var jitt: vec3f=mix( vec3f(0.0),hash(csPosition)- vec3f(0.5),roughness)*uniforms.roughnessFactor; #endif var uv2: vec2f=input.vUV*texSize;var c: f32=(uv2.x+uv2.y)*0.25;var jitter: f32=((c)%(1.0)); rayHasHit=traceScreenSpaceRay1( csPosition, normalize(csReflectedVector+jitt), uniforms.projectionPixel, depthSampler, texSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER backDepthSampler, uniforms.backSizeFactor, #endif uniforms.thickness, uniforms.nearPlaneZ, uniforms.stepSize, jitter, uniforms.maxSteps, uniforms.maxDistance, uniforms.selfCollisionNumSkip, &startPixel, &hitPixel, &hitPoint, &numIterations #ifdef SSRAYTRACE_DEBUG ,&debugColor #endif );} #ifdef SSRAYTRACE_DEBUG fragmentOutputs.color= vec4f(debugColor,1.);return fragmentOutputs; #endif var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var SSR: vec3f=envColor;if (rayHasHit) {var reflectedColor: vec3f=textureLoad(textureSampler,vec2(hitPixel),0).rgb; #ifdef SSR_INPUT_IS_GAMMA_SPACE reflectedColor=toLinearSpaceVec3(reflectedColor); #endif reflectionAttenuation*=computeAttenuationForIntersection(hitPixel,hitPixel/texSize,csPosition,hitPoint,csReflectedVector,uniforms.maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} #ifndef SSR_BLEND_WITH_FRESNEL SSR*=fresnel; #endif #ifdef SSR_USE_BLUR var blur_radius: f32=0.0;var roughness: f32=1.0-reflectivity.a*(1.0-uniforms.roughnessFactor);if (roughness>0.001) {var cone_angle: f32=min(roughness,0.999)*3.14159265*0.5;var cone_len: f32=distance(startPixel,hitPixel);var op_len: f32=2.0*tan(cone_angle)*cone_len; var a: f32=op_len;var h: f32=cone_len;var a2: f32=a*a;var fh2: f32=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} fragmentOutputs.color= vec4f(SSR,blur_radius/255.0); #else #ifdef SSR_BLEND_WITH_FRESNEL var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #else var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #endif var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpaceVec3(finalColor); #endif fragmentOutputs.color= vec4f(finalColor,colorFull.a); #endif #else fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0); #endif } `;de.ShadersStoreWGSL[fQe]=pQe;const mQe={name:fQe,shader:pQe},oRt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2PixelShaderWGSL:mQe},Symbol.toStringTag,{value:"Module"})),gQe="screenSpaceReflection2BlurPixelShader",_Qe=`var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;uniform texelOffsetScale: vec2f;const weights: array=array(0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);fn processSample(uv: vec2f,i: f32,stepSize: vec2f,accumulator: ptr,denominator: ptr) {var offsetUV: vec2f=stepSize*i+uv;var coefficient: f32=weights[ i32(2.0-abs(i))];*accumulator+=textureSampleLevel(textureSampler,textureSamplerSampler,offsetUV,0.0)*coefficient;*denominator+=coefficient;} @fragment fn main(input: FragmentInputs)->FragmentOutputs {var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);if (dot(colorFull, vec4f(1.0))==0.0) {fragmentOutputs.color=colorFull;return fragmentOutputs;} var blurRadius: f32=colorFull.a*255.0; var stepSize: vec2f=uniforms.texelOffsetScale.xy*blurRadius;var accumulator: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0)*0.214607;var denominator: f32=0.214607;processSample(input.vUV,1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*2.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*2.0,stepSize,&accumulator,&denominator);fragmentOutputs.color= vec4f(accumulator.rgb/denominator,colorFull.a);} `;de.ShadersStoreWGSL[gQe]=_Qe;const vQe={name:gQe,shader:_Qe},xMe=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurPixelShaderWGSL:vQe},Symbol.toStringTag,{value:"Module"})),yQe="screenSpaceReflection2BlurCombinerPixelShader",xQe=`var textureSamplerSampler: sampler;var textureSampler: texture_2d; var mainSamplerSampler: sampler;var mainSampler: texture_2d;var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;uniform strength: f32;uniform reflectionSpecularFalloffExponent: f32;uniform reflectivityThreshold: f32;varying vUV: vec2f; #include #ifdef SSR_BLEND_WITH_FRESNEL #include #include uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;var normalSampler: texture_2d;var depthSampler: texture_2d; #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #ifdef SSRAYTRACE_DEBUG fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV); #else var SSR: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var color: vec4f=textureSample(mainSampler,textureSamplerSampler,input.vUV);var reflectivity: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vUV); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {fragmentOutputs.color=color;return fragmentOutputs;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpaceVec4(color); #endif #ifdef SSR_BLEND_WITH_FRESNEL var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz;var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r;var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);var csViewDirection: vec3f=normalize(csPosition);var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #else var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #endif var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpaceVec3(finalColor); #endif fragmentOutputs.color= vec4f(finalColor,color.a); #endif } `;de.ShadersStoreWGSL[yQe]=xQe;const AQe={name:yQe,shader:xQe},lRt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurCombinerPixelShaderWGSL:AQe},Symbol.toStringTag,{value:"Module"}));var Ude;(function(s){s[s.Hable=0]="Hable",s[s.Reinhard=1]="Reinhard",s[s.HejiDawson=2]="HejiDawson",s[s.Photographic=3]="Photographic"})(Ude||(Ude={}));class cRt extends Ft{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,r,n=2,a,o=0,l){super(e,"tonemap",["_ExposureAdjustment"],null,1,r,n,a,l,null,o),this._operator=t,this.exposureAdjustment=i;let c="#define ";this._operator===0?c+="HABLE_TONEMAPPING":this._operator===1?c+="REINHARD_TONEMAPPING":this._operator===2?c+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===3&&(c+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(c),this.onApply=u=>{u.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>EIt),void 0)]))):t.push(Promise.all([Ue(()=>Promise.resolve().then(()=>SIt),void 0)])),super._gatherImports(e,t)}}const uRt="volumetricLightScatteringPixelShader",hRt=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i #include #include #include[0..maxSimultaneousMorphTargets] #include uniform mat4 viewProjection;uniform vec2 depthValues; #if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif } `;de.ShadersStore[dRt]=fRt;const pRt="volumetricLightScatteringPassPixelShader",mRt=`#if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV; #endif #if defined(ALPHATEST) uniform sampler2D diffuseSampler; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #if defined(ALPHATEST) vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) discard; #endif gl_FragColor=vec4(0.0,0.0,0.0,1.0);} `;de.ShadersStore[pRt]=mRt;class tf extends Ft{get useDiffuseColor(){return fe.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){fe.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,n=100,a=xe.BILINEAR_SAMPLINGMODE,o,l,c){super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,a,o,l,"#define NUM_SAMPLES "+n),this._screenCoordinates=we.Zero(),this.customMeshPosition=D.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,c=(i==null?void 0:i.getScene())??c??this._scene,o=c.getEngine(),this._viewPort=new uc(0,0,1,1).toGlobal(o.getRenderWidth(),o.getRenderHeight()),this.mesh=r??tf.CreateDefaultMesh("VolumetricLightScatteringMesh",c),this._createPass(c,t.passRatio||t),this.onActivate=u=>{this.isSupported||this.dispose(u),this.onActivate=null},this.onApplyObservable.add(u=>{this._updateMeshScreenCoordinates(c),u.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),u.setFloat("exposure",this.exposure),u.setFloat("decay",this.decay),u.setFloat("weight",this.weight),u.setFloat("density",this.density),u.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var h;const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const r=(h=i._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:h[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(i,e,t);const n=[],a=[$.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),i.isVerticesDataPresent($.UVKind)&&(a.push($.UVKind),n.push("#define UV1")),i.isVerticesDataPresent($.UV2Kind)&&(a.push($.UV2Kind),n.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(a.push($.MatricesIndicesKind),a.push($.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),n.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),A_(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const l=e._getDrawWrapper(void 0,!0),c=l.defines,u=n.join(` `);return c!==u&&l.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),u),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);t!==-1&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&this.includedMeshes.indexOf(e)===-1||this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new Rs("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=xe.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=xe.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const r=this.getCamera();r?r.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const n=l=>{var g;const c=l.getRenderingMesh(),u=l.getEffectiveMesh();if(this._meshExcluded(c))return;u._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const h=l.getMaterial();if(!h)return;const d=c.getScene(),f=d.getEngine();f.setState(h.backFaceCulling,void 0,void 0,void 0,h.cullBackFaces);const p=c._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(p.mustReturn)return;const m=f.getCaps().instancedArrays&&(p.visibleInstances[l._id]!==null||c.hasThinInstances);if(this._isReady(l,m)){const _=(g=u._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:g[f.currentRenderPassId];let y=l._getDrawWrapper();if(c===this.mesh&&!y&&(y=h._getDrawWrapper()),!y)return;const v=y.effect;if(f.enableEffect(y),m||c._bind(l,v,h.fillMode),c===this.mesh)h.bind(u.getWorldMatrix(),c);else if(_)_.bindForSubMesh(u.getWorldMatrix(),u,l);else{if(v.setMatrix("viewProjection",d.getTransformMatrix()),h&&h.needAlphaTesting()){const x=h.getAlphaTestTexture();v.setTexture("diffuseSampler",x),x&&v.setMatrix("diffuseMatrix",x.getTextureMatrix())}c.useBones&&c.computeBonesUsingShaders&&c.skeleton&&v.setMatrices("mBones",c.skeleton.getTransformMatrices(c))}m&&c.hasThinInstances&&v.setMatrix("world",u.getWorldMatrix()),c._processRendering(u,l,v,Ye.TriangleFillMode,p,m,(x,A)=>{x||v.setMatrix("world",A)})}};let a;const o=new Ze(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{a=e.clearColor,e.clearColor=o}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=a}),this._volumetricLightScatteringRTT.customIsReadyFunction=(l,c,u)=>{if((u||c===0)&&l.subMeshes)for(let h=0;h{const d=e.getEngine();let f;if(h.length){for(d.setColorWrite(!1),f=0;fm._alphaIndex>g._alphaIndex?1:m._alphaIndexg._distanceToCamera?-1:0),d.setAlphaMode(2),f=0;f{u.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),u.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const h=this._geometryBufferRenderer.getGBuffer().textures[1];u.setTexture("normalSampler",h)}):fe.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=Rt.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,r){return qe.Parse(()=>new hD(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}F([X()],hD.prototype,"ridge",void 0);F([X()],hD.prototype,"valley",void 0);ve("BABYLON.ScreenSpaceCurvaturePostProcess",hD);const bQe="postprocessVertexShader",CQe=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStoreWGSL[bQe]=CQe;const SQe={name:bQe,shader:CQe},vRt=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShaderWGSL:SQe},Symbol.toStringTag,{value:"Module"})),yRt="kernelBlurVaryingDeclaration",xRt="varying vec2 sampleCoord{X};";de.IncludesShadersStore[yRt]=xRt;const ARt="kernelBlurFragment",bRt=`#ifdef DOF factor=sampleCoC(sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; #else blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; #endif `;de.IncludesShadersStore[ARt]=bRt;const CRt="kernelBlurFragment2",SRt=`#ifdef DOF factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; #else blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif `;de.IncludesShadersStore[CRt]=SRt;const EQe="kernelBlurPixelShader",TQe=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; #ifdef DOF uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } #endif #include[0..varyingCount] #ifdef PACKEDFLOAT #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float computedWeight=0.0; #ifdef PACKEDFLOAT float blend=0.; #else vec4 blend=vec4(0.); #endif #ifdef DOF float sumOfWeights=CENTER_WEIGHT; float factor=0.0; #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; #else blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; #endif #endif #include[0..varyingCount] #include[0..depCount] #ifdef PACKEDFLOAT gl_FragColor=pack(blend); #else gl_FragColor=blend; #endif #ifdef DOF gl_FragColor/=sumOfWeights; #endif }`;de.ShadersStore[EQe]=TQe;const MQe={name:EQe,shader:TQe},ERt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurPixelShader:MQe},Symbol.toStringTag,{value:"Module"})),TRt="kernelBlurVertex",MRt="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";de.IncludesShadersStore[TRt]=MRt;const RQe="kernelBlurVertexShader",IQe=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; #include[0..varyingCount] const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN sampleCenter=(position*madd+madd); #include[0..varyingCount] gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[RQe]=IQe;const PQe={name:RQe,shader:IQe},RRt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurVertexShader:PQe},Symbol.toStringTag,{value:"Module"})),IRt="kernelBlurVaryingDeclaration",PRt="varying sampleCoord{X}: vec2f;";de.IncludesShadersStoreWGSL[IRt]=PRt;const wRt="kernelBlurFragment",DRt=`#ifdef DOF factor=sampleCoC(fragmentInputs.sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight; #else blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight; #endif `;de.IncludesShadersStoreWGSL[wRt]=DRt;const LRt="kernelBlurFragment2",ORt=`#ifdef DOF factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight; #else blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif `;de.IncludesShadersStoreWGSL[LRt]=ORt;const wQe="kernelBlurPixelShader",DQe=`var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f; #ifdef DOF var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; } #endif #include[0..varyingCount] #ifdef PACKEDFLOAT #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0; #ifdef PACKEDFLOAT var blend: f32=0.; #else var blend: vec4f= vec4f(0.); #endif #ifdef DOF var sumOfWeights: f32=CENTER_WEIGHT; var factor: f32=0.0; #ifdef PACKEDFLOAT blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT; #else blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT; #endif #endif #include[0..varyingCount] #include[0..depCount] #ifdef PACKEDFLOAT fragmentOutputs.color=pack(blend); #else fragmentOutputs.color=blend; #endif #ifdef DOF fragmentOutputs.color/=sumOfWeights; #endif }`;de.ShadersStoreWGSL[wQe]=DQe;const LQe={name:wQe,shader:DQe},NRt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurPixelShaderWGSL:LQe},Symbol.toStringTag,{value:"Module"})),FRt="kernelBlurVertex",BRt="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";de.IncludesShadersStoreWGSL[FRt]=BRt;const OQe="kernelBlurVertexShader",NQe=`attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f; #include[0..varyingCount] #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.sampleCenter=(input.position*madd+madd); #include[0..varyingCount] vertexOutputs.position= vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[OQe]=NQe;const FQe={name:OQe,shader:NQe},kRt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurVertexShaderWGSL:FQe},Symbol.toStringTag,{value:"Module"})),BQe="passCubePixelShader",kQe=`varying vec2 vUV;uniform samplerCube textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 uv=vUV*2.0-1.0; #ifdef POSITIVEX gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); #endif #ifdef NEGATIVEX gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); #endif #ifdef POSITIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); #endif #ifdef NEGATIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); #endif #ifdef POSITIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); #endif #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); #endif }`;de.ShadersStore[BQe]=kQe;const UQe={name:BQe,shader:kQe},URt=Object.freeze(Object.defineProperty({__proto__:null,passCubePixelShader:UQe},Symbol.toStringTag,{value:"Module"})),zQe="passPixelShader",VQe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`;de.ShadersStoreWGSL[zQe]=VQe;const GQe={name:zQe,shader:VQe},zRt=Object.freeze(Object.defineProperty({__proto__:null,passPixelShaderWGSL:GQe},Symbol.toStringTag,{value:"Module"})),WQe="passCubePixelShader",KQe=`varying var vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0; #ifdef POSITIVEX fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x)); #endif #ifdef NEGATIVEX fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x)); #endif #ifdef POSITIVEY fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x)); #endif #ifdef NEGATIVEY fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x)); #endif #ifdef POSITIVEZ fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001)); #endif #ifdef NEGATIVEZ fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001)); #endif }`;de.ShadersStoreWGSL[WQe]=KQe;const HQe={name:WQe,shader:KQe},VRt=Object.freeze(Object.defineProperty({__proto__:null,passCubePixelShaderWGSL:HQe},Symbol.toStringTag,{value:"Module"})),jQe="vrDistortionCorrectionPixelShader",XQe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;de.ShadersStore[jQe]=XQe;const YQe={name:jQe,shader:XQe},GRt=Object.freeze(Object.defineProperty({__proto__:null,vrDistortionCorrectionPixelShader:YQe},Symbol.toStringTag,{value:"Module"})),QQe="vrDistortionCorrectionPixelShader",$Qe=`#define DISABLE_UNIFORMITY_ANALYSIS varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform LensCenter: vec2f;uniform Scale: vec2f;uniform ScaleIn: vec2f;uniform HmdWarpParam: vec4f;fn HmdWarp(in01: vec2f)->vec2f {var theta: vec2f=(in01-uniforms.LensCenter)*uniforms.ScaleIn; var rSq: f32=theta.x*theta.x+theta.y*theta.y;var rvector: vec2f=theta*(uniforms.HmdWarpParam.x+uniforms.HmdWarpParam.y*rSq+uniforms.HmdWarpParam.z*rSq*rSq+uniforms.HmdWarpParam.w*rSq*rSq*rSq);return uniforms.LensCenter+uniforms.Scale*rvector;} #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var tc: vec2f=HmdWarp(input.vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) {fragmentOutputs.color=vec4f(0.0,0.0,0.0,0.0);} else{fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,tc);}}`;de.ShadersStoreWGSL[QQe]=$Qe;const ZQe={name:QQe,shader:$Qe},WRt=Object.freeze(Object.defineProperty({__proto__:null,vrDistortionCorrectionPixelShaderWGSL:ZQe},Symbol.toStringTag,{value:"Module"})),qQe="imageProcessingPixelShader",JQe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); #ifdef IMAGEPROCESSING #ifndef FROMLINEARSPACE result=vec4f(toLinearSpaceVec3(result.rgb),result.a); #endif result=applyImageProcessing(result); #else #ifdef FROMLINEARSPACE result=applyImageProcessing(result); #endif #endif fragmentOutputs.color=result;}`;de.ShadersStoreWGSL[qQe]=JQe;const e$e={name:qQe,shader:JQe},KRt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingPixelShaderWGSL:e$e},Symbol.toStringTag,{value:"Module"})),t$e="imageProcessingPixelShader",i$e=`varying vec2 vUV;uniform sampler2D textureSampler; #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 result=texture2D(textureSampler,vUV); #ifdef IMAGEPROCESSING #ifndef FROMLINEARSPACE result.rgb=toLinearSpace(result.rgb); #endif result=applyImageProcessing(result); #else #ifdef FROMLINEARSPACE result=applyImageProcessing(result); #endif #endif gl_FragColor=result;}`;de.ShadersStore[t$e]=i$e;const r$e={name:t$e,shader:i$e},HRt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingPixelShader:r$e},Symbol.toStringTag,{value:"Module"})),s$e="sharpenPixelShader",n$e=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform sharpnessAmounts: vec2f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var edgeDetection: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,-1)) + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(-1,0)) + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(1,0)) + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,1)) - color*4.0;fragmentOutputs.color=max(vec4f(color.rgb*uniforms.sharpnessAmounts.y,color.a)-(uniforms.sharpnessAmounts.x* vec4f(edgeDetection.rgb,0)),vec4f(0.));}`;de.ShadersStoreWGSL[s$e]=n$e;const a$e={name:s$e,shader:n$e},jRt=Object.freeze(Object.defineProperty({__proto__:null,sharpenPixelShaderWGSL:a$e},Symbol.toStringTag,{value:"Module"})),o$e="grainPixelShader",l$e=`#include uniform sampler2D textureSampler; uniform float intensity;uniform float animatedSeed;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;de.ShadersStore[o$e]=l$e;const c$e={name:o$e,shader:l$e},XRt=Object.freeze(Object.defineProperty({__proto__:null,grainPixelShader:c$e},Symbol.toStringTag,{value:"Module"})),u$e="grainPixelShader",h$e=`#include varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform intensity: f32;uniform animatedSeed: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var seed: vec2f=input.vUV*uniforms.animatedSeed;var grain: f32=dither(seed,uniforms.intensity);var lum: f32=getLuminance(fragmentOutputs.color.rgb);var grainAmount: f32=(cos(-PI+(lum*PI*2.))+1.)/2.;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+grain*grainAmount,fragmentOutputs.color.a);fragmentOutputs.color=vec4f(max(fragmentOutputs.color.rgb,vec3f(0.0)),fragmentOutputs.color.a);}`;de.ShadersStoreWGSL[u$e]=h$e;const d$e={name:u$e,shader:h$e},YRt=Object.freeze(Object.defineProperty({__proto__:null,grainPixelShaderWGSL:d$e},Symbol.toStringTag,{value:"Module"})),f$e="chromaticAberrationPixelShader",p$e=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform chromatic_aberration: f32;uniform radialIntensity: f32;uniform direction: vec2f;uniform centerPosition: vec2f;uniform screen_width: f32;uniform screen_height: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var centered_screen_pos: vec2f= vec2f(input.vUV.x-uniforms.centerPosition.x,input.vUV.y-uniforms.centerPosition.y);var directionOfEffect: vec2f=uniforms.direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} var radius2: f32=centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;var radius: f32=sqrt(radius2);var ref_indices: vec3f= vec3f(-0.3,0.0,0.3);var ref_shiftX: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.x/uniforms.screen_width;var ref_shiftY: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.y/uniforms.screen_height;var ref_coords_r: vec2f=vec2f(input.vUV.x+ref_indices.r*ref_shiftX,input.vUV.y+ref_indices.r*ref_shiftY*0.5);var ref_coords_g: vec2f=vec2f(input.vUV.x+ref_indices.g*ref_shiftX,input.vUV.y+ref_indices.g*ref_shiftY*0.5);var ref_coords_b: vec2f=vec2f(input.vUV.x+ref_indices.b*ref_shiftX,input.vUV.y+ref_indices.b*ref_shiftY*0.5);var r=textureSample(textureSampler,textureSamplerSampler,ref_coords_r);var g=textureSample(textureSampler,textureSamplerSampler,ref_coords_g);var b=textureSample(textureSampler,textureSamplerSampler,ref_coords_b);var a=clamp(r.a+g.a+b.a,0.,1.);fragmentOutputs.color=vec4f(r.r,g.g,b.b,a);}`;de.ShadersStoreWGSL[f$e]=p$e;const m$e={name:f$e,shader:p$e},QRt=Object.freeze(Object.defineProperty({__proto__:null,chromaticAberrationPixelShaderWGSL:m$e},Symbol.toStringTag,{value:"Module"})),g$e="depthOfFieldMergePixelShader",_$e=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; #if BLUR_LEVEL>0 uniform sampler2D blurStep1; #endif #if BLUR_LEVEL>1 uniform sampler2D blurStep2; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; #if BLUR_LEVEL==0 vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); #endif #if BLUR_LEVEL==1 if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} #endif #if BLUR_LEVEL==2 if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} #endif } `;de.ShadersStore[g$e]=_$e;const v$e={name:g$e,shader:_$e},$Rt=Object.freeze(Object.defineProperty({__proto__:null,depthOfFieldMergePixelShader:v$e},Symbol.toStringTag,{value:"Module"})),y$e="depthOfFieldMergePixelShader",x$e=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;var blurStep0Sampler: sampler;var blurStep0: texture_2d; #if BLUR_LEVEL>0 var blurStep1Sampler: sampler;var blurStep1: texture_2d; #endif #if BLUR_LEVEL>1 var blurStep2Sampler: sampler;var blurStep2: texture_2d; #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var coc: f32=textureSampleLevel(circleOfConfusionSampler,circleOfConfusionSamplerSampler,input.vUV,0.0).r; #if BLUR_LEVEL==0 var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred0,coc); #endif #if BLUR_LEVEL==1 if(coc<0.5){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred1,coc/0.5);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.5)/0.5);} #endif #if BLUR_LEVEL==2 if(coc<0.33){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred2,coc/0.33);}else if(coc<0.66){var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.66)/0.34);} #endif } `;de.ShadersStoreWGSL[y$e]=x$e;const A$e={name:y$e,shader:x$e},ZRt=Object.freeze(Object.defineProperty({__proto__:null,depthOfFieldMergePixelShaderWGSL:A$e},Symbol.toStringTag,{value:"Module"})),b$e="circleOfConfusionPixelShader",C$e=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float depth=texture2D(depthSampler,vUV).r; #define CUSTOM_COC_DEPTH float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; #define CUSTOM_COC_PIXELDISTANCE float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} `;de.ShadersStore[b$e]=C$e;const S$e={name:b$e,shader:C$e},qRt=Object.freeze(Object.defineProperty({__proto__:null,circleOfConfusionPixelShader:S$e},Symbol.toStringTag,{value:"Module"})),E$e="circleOfConfusionPixelShader",T$e=`varying vUV: vec2f;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform cameraMinMaxZ: vec2f;uniform focusDistance: f32;uniform cocPrecalculation: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r; #define CUSTOM_COC_DEPTH var pixelDistance: f32=(uniforms.cameraMinMaxZ.x+uniforms.cameraMinMaxZ.y*depth)*1000.0; #define CUSTOM_COC_PIXELDISTANCE var coc: f32=abs(uniforms.cocPrecalculation*((uniforms.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);fragmentOutputs.color= vec4f(coc,coc,coc,1.0);} `;de.ShadersStoreWGSL[E$e]=T$e;const M$e={name:E$e,shader:T$e},JRt=Object.freeze(Object.defineProperty({__proto__:null,circleOfConfusionPixelShaderWGSL:M$e},Symbol.toStringTag,{value:"Module"})),R$e="bloomMergePixelShader",I$e=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } `;de.ShadersStore[R$e]=I$e;const P$e={name:R$e,shader:I$e},eIt=Object.freeze(Object.defineProperty({__proto__:null,bloomMergePixelShader:P$e},Symbol.toStringTag,{value:"Module"})),w$e="bloomMergePixelShader",D$e=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var bloomBlurSampler: sampler;var bloomBlur: texture_2d;uniform bloomWeight: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);} `;de.ShadersStoreWGSL[w$e]=D$e;const L$e={name:w$e,shader:D$e},tIt=Object.freeze(Object.defineProperty({__proto__:null,bloomMergePixelShaderWGSL:L$e},Symbol.toStringTag,{value:"Module"})),O$e="extractHighlightsPixelShader",N$e=`#include varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;de.ShadersStore[O$e]=N$e;const F$e={name:O$e,shader:N$e},iIt=Object.freeze(Object.defineProperty({__proto__:null,extractHighlightsPixelShader:F$e},Symbol.toStringTag,{value:"Module"})),B$e="extractHighlightsPixelShader",k$e=`#include varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform threshold: f32;uniform exposure: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}`;de.ShadersStoreWGSL[B$e]=k$e;const U$e={name:B$e,shader:k$e},rIt=Object.freeze(Object.defineProperty({__proto__:null,extractHighlightsPixelShaderWGSL:U$e},Symbol.toStringTag,{value:"Module"})),z$e="fxaaPixelShader",V$e=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); #define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); #ifndef MALI if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) {lumaN=lumaW;} if (!horzSpan) {lumaS=lumaE;} if (horzSpan) {lengthSign=texelSize.y;} float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) {lengthSign=-lengthSign;} float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) {posB.x+=lengthSign*0.5;} if (horzSpan) {posB.y+=lengthSign*0.5;} vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) {lumaNN=lumaSS;} float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*3.0;} if (!doneN) {posN.y-=offNP.y*3.0;} bool doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*3.0;} if (!doneP) {posP.y+=offNP.y*3.0;} if (doneNP) {if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) {dstN=posM.y-posN.y;} if (!horzSpan) {dstP=posP.y-posM.y;} bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);} @fragment fn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); #ifndef MALI if(range=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) {lumaN=lumaW;} if (!horzSpan) {lumaS=lumaE;} if (horzSpan) {lengthSign=uniforms.texelSize.y;} var subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN) {lengthSign=-lengthSign;} var subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan) {posB.x+=lengthSign*0.5;} if (horzSpan) {posB.y+=lengthSign*0.5;} var posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN) {lumaNN=lumaSS;} var gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*3.0;} if (!doneN) {posN.y-=offNP.y*3.0;} var doneNP: bool=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*3.0;} if (!doneP) {posP.y+=offNP.y*3.0;} if (doneNP) {if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));} if (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));} if (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;} if (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;} doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;} if (!doneN) {posN.y-=offNP.y*12.0;} doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;} if (!doneP) {posP.y+=offNP.y*12.0;}} var dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan) {dstN=posM.y-posN.y;} if (!horzSpan) {dstP=posP.y-posM.y;} var goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstNFragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=(input.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[Q$e]=$$e;const Z$e={name:Q$e,shader:$$e},oIt=Object.freeze(Object.defineProperty({__proto__:null,fxaaVertexShaderWGSL:Z$e},Symbol.toStringTag,{value:"Module"})),q$e="blackAndWhitePixelShader",J$e=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;de.ShadersStore[q$e]=J$e;const eZe={name:q$e,shader:J$e},lIt=Object.freeze(Object.defineProperty({__proto__:null,blackAndWhitePixelShader:eZe},Symbol.toStringTag,{value:"Module"})),tZe="blackAndWhitePixelShader",iZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform degree: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var luminance: f32=dot(color, vec3f(0.3,0.59,0.11)); var blackAndWhite: vec3f= vec3f(luminance,luminance,luminance);fragmentOutputs.color= vec4f(color-((color-blackAndWhite)*uniforms.degree),1.0);}`;de.ShadersStoreWGSL[tZe]=iZe;const rZe={name:tZe,shader:iZe},cIt=Object.freeze(Object.defineProperty({__proto__:null,blackAndWhitePixelShaderWGSL:rZe},Symbol.toStringTag,{value:"Module"})),sZe="anaglyphPixelShader",nZe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;de.ShadersStore[sZe]=nZe;const aZe={name:sZe,shader:nZe},uIt=Object.freeze(Object.defineProperty({__proto__:null,anaglyphPixelShader:aZe},Symbol.toStringTag,{value:"Module"})),oZe="anaglyphPixelShader",lZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var leftSamplerSampler: sampler;var leftSampler: texture_2d; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var leftFrag: vec4f=textureSample(leftSampler,leftSamplerSampler,input.vUV);leftFrag= vec4f(1.0,leftFrag.g,leftFrag.b,1.0);var rightFrag: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);rightFrag= vec4f(rightFrag.r,1.0,1.0,1.0);fragmentOutputs.color= vec4f(rightFrag.rgb*leftFrag.rgb,1.0);}`;de.ShadersStoreWGSL[oZe]=lZe;const cZe={name:oZe,shader:lZe},hIt=Object.freeze(Object.defineProperty({__proto__:null,anaglyphPixelShaderWGSL:cZe},Symbol.toStringTag,{value:"Module"})),uZe="convolutionPixelShader",hZe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = kernel[0] + kernel[1] + kernel[2] + kernel[3] + kernel[4] + kernel[5] + kernel[6] + kernel[7] + kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;de.ShadersStore[uZe]=hZe;const dZe={name:uZe,shader:hZe},dIt=Object.freeze(Object.defineProperty({__proto__:null,convolutionPixelShader:dZe},Symbol.toStringTag,{value:"Module"})),fZe="convolutionPixelShader",pZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform kernel: array; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var colorSum: vec4f = textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,-1))*uniforms.kernel[0] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,-1))*uniforms.kernel[1] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,-1))*uniforms.kernel[2] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,0))*uniforms.kernel[3] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,0))*uniforms.kernel[4] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,0))*uniforms.kernel[5] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,1))*uniforms.kernel[6] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,1))*uniforms.kernel[7] + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,1))*uniforms.kernel[8];var kernelWeight: f32 = uniforms.kernel[0] + uniforms.kernel[1] + uniforms.kernel[2] + uniforms.kernel[3] + uniforms.kernel[4] + uniforms.kernel[5] + uniforms.kernel[6] + uniforms.kernel[7] + uniforms.kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} fragmentOutputs.color= vec4f((colorSum/kernelWeight).rgb,1);}`;de.ShadersStoreWGSL[fZe]=pZe;const mZe={name:fZe,shader:pZe},fIt=Object.freeze(Object.defineProperty({__proto__:null,convolutionPixelShaderWGSL:mZe},Symbol.toStringTag,{value:"Module"})),gZe="colorCorrectionPixelShader",_Ze=`uniform sampler2D textureSampler; uniform sampler2D colorTable; varying vec2 vUV;const float SLICE_COUNT=16.0; vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; float slicePixelSize=sliceSize/width; float sliceInnerSize=slicePixelSize*(width-1.0); float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;de.ShadersStore[gZe]=_Ze;const vZe={name:gZe,shader:_Ze},pIt=Object.freeze(Object.defineProperty({__proto__:null,colorCorrectionPixelShader:vZe},Symbol.toStringTag,{value:"Module"})),yZe="colorCorrectionPixelShader",xZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;var colorTableSampler: sampler;var colorTable: texture_2d;const SLICE_COUNT: f32=16.0; fn sampleAs3DTexture(uv: vec3f,width: f32)->vec4f {var sliceSize: f32=1.0/width; var slicePixelSize: f32=sliceSize/width; var sliceInnerSize: f32=slicePixelSize*(width-1.0); var zSlice0: f32=min(floor(uv.z*width),width-1.0);var zSlice1: f32=min(zSlice0+1.0,width-1.0);var xOffset: f32=slicePixelSize*0.5+uv.x*sliceInnerSize;var s0: f32=xOffset+(zSlice0*sliceSize);var s1: f32=xOffset+(zSlice1*sliceSize);var slice0Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s0,uv.y));var slice1Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s1,uv.y));var zOffset: f32=((uv.z*width)%(1.0));return mix(slice0Color,slice1Color,zOffset);} #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var screen_color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=sampleAs3DTexture(screen_color.rgb,SLICE_COUNT);}`;de.ShadersStoreWGSL[yZe]=xZe;const AZe={name:yZe,shader:xZe},mIt=Object.freeze(Object.defineProperty({__proto__:null,colorCorrectionPixelShaderWGSL:AZe},Symbol.toStringTag,{value:"Module"})),bZe="motionBlurPixelShader",CZe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; #ifdef OBJECT_BASED uniform sampler2D velocitySampler; #else uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #ifdef GEOMETRY_SUPPORTED #ifdef OBJECT_BASED vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) break;vec2 offset=vUV+velocity*(hlim+float(i)); #if defined(WEBGPU) result+=texture2DLodEXT(textureSampler,offset,0.0); #else result+=texture2D(textureSampler,offset); #endif } gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; #else vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); #if defined(WEBGPU) result+=texture2DLodEXT(textureSampler,offset1,0.0); #else result+=texture2D(textureSampler,offset1); #endif } gl_FragColor=result/float(nSamples); #endif #else gl_FragColor=texture2D(textureSampler,vUV); #endif } `;de.ShadersStore[bZe]=CZe;const SZe={name:bZe,shader:CZe},gIt=Object.freeze(Object.defineProperty({__proto__:null,motionBlurPixelShader:SZe},Symbol.toStringTag,{value:"Module"})),EZe="motionBlurPixelShader",TZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform motionStrength: f32;uniform motionScale: f32;uniform screenSize: vec2f; #ifdef OBJECT_BASED var velocitySamplerSampler: sampler;var velocitySampler: texture_2d; #else var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform inverseViewProjection: mat4x4f;uniform prevViewProjection: mat4x4f;uniform projection: mat4x4f; #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #ifdef GEOMETRY_SUPPORTED #ifdef OBJECT_BASED var texelSize: vec2f=1.0/uniforms.screenSize;var velocityColor: vec4f=textureSample(velocitySampler,velocitySamplerSampler,input.vUV);velocityColor=vec4f(velocityColor.rg*2.0- vec2f(1.0),velocityColor.b,velocityColor.a);var velocity: vec2f= vec2f(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var samplesCount: i32= i32(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;var hlim: f32= f32(-samplesCount)*0.5+0.5;var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=samplesCount) {break;} var offset: vec2f=input.vUV+velocity*(hlim+ f32(i)); #if defined(WEBGPU) result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset,0.0); #else result+=textureSample(textureSampler,textureSamplerSampler, offset); #endif } fragmentOutputs.color=vec4f(result.rgb/ f32(samplesCount),1.0); #else var texelSize: vec2f=1.0/uniforms.screenSize;var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;depth=uniforms.projection[2].z+uniforms.projection[3].z/depth; var cpos: vec4f= vec4f(input.vUV*2.0-1.0,depth,1.0);cpos=uniforms.inverseViewProjection*cpos;cpos/=cpos.w;var ppos: vec4f=uniforms.prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;var velocity: vec2f=(ppos.xy-input.vUV)*uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var nSamples: i32= i32(clamp(speed,1.0,SAMPLES));var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=nSamples) {break;} var offset1: vec2f=input.vUV+velocity*( f32(i)/ f32(nSamples-1)-0.5); #if defined(WEBGPU) result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset1,0.0); #else result+=textureSample(textureSampler,textureSamplerSampler, offset1); #endif } fragmentOutputs.color=result/ f32(nSamples); #endif #else fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler, input.vUV); #endif } `;de.ShadersStoreWGSL[EZe]=TZe;const MZe={name:EZe,shader:TZe},_It=Object.freeze(Object.defineProperty({__proto__:null,motionBlurPixelShaderWGSL:MZe},Symbol.toStringTag,{value:"Module"})),RZe="filterPixelShader",IZe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;de.ShadersStore[RZe]=IZe;const PZe={name:RZe,shader:IZe},vIt=Object.freeze(Object.defineProperty({__proto__:null,filterPixelShader:PZe},Symbol.toStringTag,{value:"Module"})),wZe="filterPixelShader",DZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform kernelMatrix: mat4x4f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var baseColor: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var updatedColor: vec3f=(uniforms.kernelMatrix* vec4f(baseColor,1.0)).rgb;fragmentOutputs.color= vec4f(updatedColor,1.0);}`;de.ShadersStoreWGSL[wZe]=DZe;const LZe={name:wZe,shader:DZe},yIt=Object.freeze(Object.defineProperty({__proto__:null,filterPixelShaderWGSL:LZe},Symbol.toStringTag,{value:"Module"})),OZe="highlightsPixelShader",NZe=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;de.ShadersStore[OZe]=NZe;const FZe={name:OZe,shader:NZe},xIt=Object.freeze(Object.defineProperty({__proto__:null,highlightsPixelShader:FZe},Symbol.toStringTag,{value:"Module"})),BZe="highlightsPixelShader",kZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;const RGBLuminanceCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722); #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var tex: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var c: vec3f=tex.rgb;var luma: f32=dot(c.rgb,RGBLuminanceCoefficients);fragmentOutputs.color= vec4f(pow(c, vec3f(25.0-luma*15.0)),tex.a); }`;de.ShadersStoreWGSL[BZe]=kZe;const UZe={name:BZe,shader:kZe},AIt=Object.freeze(Object.defineProperty({__proto__:null,highlightsPixelShaderWGSL:UZe},Symbol.toStringTag,{value:"Module"})),zZe="displayPassPixelShader",VZe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(passSampler,vUV);}`;de.ShadersStore[zZe]=VZe;const GZe={name:zZe,shader:VZe},bIt=Object.freeze(Object.defineProperty({__proto__:null,displayPassPixelShader:GZe},Symbol.toStringTag,{value:"Module"})),WZe="displayPassPixelShader",KZe=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var passSamplerSampler: sampler;var passSampler: texture_2d; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(passSampler,passSamplerSampler,input.vUV);}`;de.ShadersStoreWGSL[WZe]=KZe;const HZe={name:WZe,shader:KZe},CIt=Object.freeze(Object.defineProperty({__proto__:null,displayPassPixelShaderWGSL:HZe},Symbol.toStringTag,{value:"Module"})),jZe="tonemapPixelShader",XZe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; #if defined(HABLE_TONEMAPPING) 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; #endif float Luminance(vec3 c) {return dot(c,vec3(0.22,0.707,0.071));} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec3 colour=texture2D(textureSampler,vUV).rgb; #if defined(REINHARD_TONEMAPPING) float lum=Luminance(colour.rgb); float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); colour*=scale/lum; #elif defined(HABLE_TONEMAPPING) colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; #elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; #elif defined(PHOTOGRAPHIC_TONEMAPPING) colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); #endif gl_FragColor=vec4(colour.rgb,1.0);}`;de.ShadersStore[jZe]=XZe;const YZe={name:jZe,shader:XZe},SIt=Object.freeze(Object.defineProperty({__proto__:null,tonemapPixelShader:YZe},Symbol.toStringTag,{value:"Module"})),QZe="tonemapPixelShader",$Ze=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform _ExposureAdjustment: f32; #if defined(HABLE_TONEMAPPING) 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; #endif fn Luminance(c: vec3f)->f32 {return dot(c, vec3f(0.22,0.707,0.071));} #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var colour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb; #if defined(REINHARD_TONEMAPPING) var lum: f32=Luminance(colour.rgb); var lumTm: f32=lum*uniforms._ExposureAdjustment;var scale: f32=lumTm/(1.0+lumTm); colour*=scale/lum; #elif defined(HABLE_TONEMAPPING) colour*=uniforms._ExposureAdjustment;const ExposureBias: f32=2.0;var x: vec3f=ExposureBias*colour;var curr: vec3f=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x= vec3f(W,W,W);var whiteScale: vec3f=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; #elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) colour*=uniforms._ExposureAdjustment;var X: vec3f=max( vec3f(0.0,0.0,0.0),colour-0.004);var retColor: vec3f=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; #elif defined(PHOTOGRAPHIC_TONEMAPPING) colour= vec3f(1.0,1.0,1.0)-exp2(-uniforms._ExposureAdjustment*colour); #endif fragmentOutputs.color= vec4f(colour.rgb,1.0);}`;de.ShadersStoreWGSL[QZe]=$Ze;const ZZe={name:QZe,shader:$Ze},EIt=Object.freeze(Object.defineProperty({__proto__:null,tonemapPixelShaderWGSL:ZZe},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(gt.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(s){this._forceShowBoundingBoxes=s,s&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});gt.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new qZe(this)),this._boundingBoxRenderer};Object.defineProperty(Li.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(s){this._showBoundingBox=s,s&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class qZe{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=ot.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Re(1,1,1),this.backColor=new Re(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new Ae,this.onAfterBoxRenderingObservable=new Ae,this.onResourcesReadyObservable=new Ae,this.enabled=!0,this._shaderLanguage=0,this.renderList=new no(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,this.scene.getEngine().isWebGPU&&(this._shaderLanguage=1),e._addComponent(this),this._uniformBufferFront=new zt(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new zt(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!0),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(ot.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ot.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ot.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ot.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();i!=null&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new na("colorShader",this.scene,"boundingBoxRenderer",{attributes:[$.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>SMe),void 0),Ue(()=>Promise.resolve().then(()=>CMe),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>bMe),void 0),Ue(()=>Promise.resolve().then(()=>AMe),void 0)])}},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new na("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[$.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>SMe),void 0),Ue(()=>Promise.resolve().then(()=>CMe),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>bMe),void 0),Ue(()=>Promise.resolve().then(()=>AMe),void 0)])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=$J({size:1});this._vertexBuffers[$.PositionKind]=new $(e,t.positions,$.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[$.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let r=0;r{let e=s._getComponent(ot.NAME_DEPTHRENDERER);e||(e=new JZe(s),s._addComponent(e))};const TIt="oitFinalPixelShader",MIt=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( frontColor.rgb+alphaMultiplier*backColor.rgb, frontColor.a+backColor.a );}`;de.ShadersStore[TIt]=MIt;const RIt="oitBackBlendPixelShader",IIt=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { discard;}}`;de.ShadersStore[RIt]=IIt;class PIt{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class j1{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new no(10),this._excludedSubMeshes=new no(10),this._excludedMeshes=[],this._colorCache=[new Ze(j1._DEPTH_CLEAR_VALUE,j1._DEPTH_CLEAR_VALUE,0,0),new Ze(-j1._MIN_DEPTH,j1._MAX_DEPTH,0,0),new Ze(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){fe.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i{t===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>F5t),void 0),Ue(()=>Promise.resolve().then(()=>N5t),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>O5t),void 0),Ue(()=>Promise.resolve().then(()=>I5t),void 0)])}},!1);i.disableDepthWrite=!0,i.backFaceCulling=!1,i.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=i}return e._edgeRenderLineShader}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=.95,i=!1,r=!0,n){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new no(32),this._shaderLanguage=0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=n??null,this._epsilon=t;const a=this._source.getScene().getEngine();a.isWebGPU&&(this._drawWrapper=new Ro(a),this._shaderLanguage=1),this._prepareRessources(),r&&((n==null?void 0:n.useAlternateEdgeFinder)??!0?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=oV._GetShader(this._source.getScene(),this._shaderLanguage))}_rebuild(){let e=this._buffers[$.PositionKind];e&&e._rebuild(),e=this._buffers[$.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var t;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[$.PositionKind];e&&(e.dispose(),this._buffers[$.PositionKind]=null),e=this._buffers[$.NormalKind],e&&(e.dispose(),this._buffers[$.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.dispose()}_processEdgeForAdjacencies(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,n){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(n,1e-10)||e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(n,1e-10)?2:-1}_checkEdge(e,t,i,r,n){let a;t===void 0?a=!0:a=D.Dot(i[e],i[t]){P>=0&&w.push(P);for(let M=0;M=e[0].length&&e[1].length>=e[2].length?a=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(a=2);for(let T=0;T<3;++T)T===a?e[T].sort((w,P)=>w[1]P[1]?1:0):e[T].sort((w,P)=>w[1]>P[1]?-1:w[1]=a+1;--T)n(e[T%3],l,T!==a+2?r[i[t+(T+1)%3]]:-1);const u=l.length,h=0,d=0;i.push(r[i[t+a]],o[0],l[0]),i.push(r[i[t+(a+1)%3]],l[u-1],o[c-1]);const f=c<=u,p=f?c:u,m=f?u:c,g=f?c-1:u-1,_=f?0:1;let y=c+u-2,v=f?h:d,x=f?d:h;const A=f?o:l,b=f?l:o;let C=0;for(;y-- >0;){_?i.push(A[v],b[x]):i.push(b[x],A[v]),C+=p;let T;C>=m&&vv){const C=y;y=v,v=C}const A=y+"_"+v,b=o[A];b?b.done||(D.Dot(g,b.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}const i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances;let n=0;if(r)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const o=this._source._instanceDataStorage;if(n=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let l=0;for(let c=0;c0&&(this._useSpecificClearForDepthTexture&&this._mrtLayout[n]===5?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;el!=null),this._scene.autoClear=!0;const r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const n=this._getFirstPostProcess(this._postProcessesSourceForThisPass),a=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),a?o=a:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:n&&(o=n),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;er!=null),t)){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw vi("PrePassRendererSceneComponent")};oc.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}];Object.defineProperty(gt.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(s){s&&s.isSupported&&(this._prePassRenderer=s)},enumerable:!0,configurable:!0});gt.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new oc(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,fe.Error(`PrePassRenderer needs WebGL 2 support. Maybe you tried to use the following features that need the PrePassRenderer : + Subsurface Scattering`)),this._prePassRenderer)};gt.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class iqe{constructor(e){this.name=ot.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ot.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ot.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ot.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ot.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ot.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ot.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ot.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ot.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;const n=e.getScene();n.prePassRenderer&&n.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}oc._SceneComponentInitialization=s=>{let e=s._getComponent(ot.NAME_PREPASSRENDERER);e||(e=new iqe(s),s._addComponent(e))};const LIt="fibonacci",OIt=`#define rcp(x) 1./x #define GOLDEN_RATIO 1.618033988749895 #define TWO_PI 6.2831855 vec2 Golden2dSeq(int i,float n) {return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} vec2 SampleDiskGolden(int i,int sampleCount) {vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;de.IncludesShadersStore[LIt]=OIt;const NIt="diffusionProfile",FIt="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";de.IncludesShadersStore[NIt]=FIt;const BIt="subSurfaceScatteringPixelShader",kIt=`#include #include #include #include varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; #define rcp(x) 1./x #define Sq(x) x*x #define SSS_BILATERAL_FILTER true vec3 EvalBurleyDiffusionProfile(float r,vec3 S) {vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); vec3 expSum=exp_13*(1.+exp_13*exp_13); return (S*rcp(8.*PI))*expSum; } vec2 SampleBurleyDiffusionProfile(float u,float rcpS) {u=1.-u; float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); float p=(g*n)*n; float c=1.+p+n; float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); float x=(3./LOG2_E)*log2(c)-d; float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; return vec2(r,rcpPdf);} vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) { #ifndef SSS_BILATERAL_FILTER z=0.; #endif float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; #if SSS_CLAMP_ARTIFACT return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); #else return EvalBurleyDiffusionProfile(r,S)*area; #endif } void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) {float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) {float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} else {}} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) {centerDepth=texture2D(depthSampler,vUV).r;} if (!passedStencilTest) { gl_FragColor=inputColor;return;} float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) { #ifdef DEBUG_SSS_SAMPLES vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; #endif gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} #ifdef DEBUG_SSS_SAMPLES vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; #endif float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration){fe.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}const u=this.texelSize;c.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),c.setFloat2("texelSize",u.x,u.y),c.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),c.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),c.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),c.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),c.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),c.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),c.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class lV{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=ot.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Re(1,1,1)),this._scene=e,lV._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return fe.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw vi("SubSurfaceSceneComponent")};Oa.AddParser(ot.NAME_SUBSURFACE,(s,e)=>{if(s.ssDiffusionProfileColors!==void 0&&s.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=s.ssDiffusionProfileColors.length;t{let e=s._getComponent(ot.NAME_SUBSURFACE);e||(e=new rqe(s),s._addComponent(e))};gt.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new pw(this)),this._outlineRenderer};Object.defineProperty(Ee.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(s){s&&this.getScene().getOutlineRenderer(),this._renderOutline=s},enumerable:!0,configurable:!0});Object.defineProperty(Ee.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(s){s&&this.getScene().getOutlineRenderer(),this._renderOverlay=s},enumerable:!0,configurable:!0});class pw{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=ot.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this._shaderLanguage=0,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let i=0;i<4;++i)this._passIdForDrawWrapper[i]=this._engine.createRenderPassId(`Outline Renderer (${i})`);this._engine.isWebGPU&&(this._shaderLanguage=1)}register(){this.scene._beforeRenderingMeshStage.registerStep(ot.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ot.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",_)}),a.setZOffset(0),a.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const r=[],n=[$.PositionKind,$.NormalKind],a=e.getMesh(),o=e.getMaterial();if(!o)return!1;const l=a.getScene();o.needAlphaTesting()&&(r.push("#define ALPHATEST"),a.isVerticesDataPresent($.UVKind)&&(n.push($.UVKind),r.push("#define UV1")),a.isVerticesDataPresent($.UV2Kind)&&(n.push($.UV2Kind),r.push("#define UV2"))),o.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),t3(o,l,r);const c=new oa;if(a.useBones&&a.computeBonesUsingShaders&&a.skeleton){n.push($.MatricesIndicesKind),n.push($.MatricesWeightsKind),a.numBoneInfluencers>4&&(n.push($.MatricesIndicesExtraKind),n.push($.MatricesWeightsExtraKind));const g=a.skeleton;r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),a.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,a),g.isUsingTextureForMatrices?r.push("#define BONETEXTURE"):r.push("#define BonesPerMesh "+(g.bones.length+1))}else r.push("#define NUM_BONE_INFLUENCERS 0");const u=a.morphTargetManager;let h=0;u&&(h=u.numMaxInfluencers||u.numInfluencers,h>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),u.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),rT(n,a,h))),t&&(r.push("#define INSTANCES"),A_(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const d=a.bakedVertexAnimationManager;t&&d&&d.isEnabled&&(r.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),n.push("bakedVertexAnimationSettingsInstanced"));const f=e._getDrawWrapper(i,!0),p=f.defines,m=r.join(` `);if(p!==m){const g=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],_=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"];fo(g),f.setEffect(this.scene.getEngine().createEffect("outline",{attributes:n,uniformsNames:g,uniformBuffersNames:[],samplers:_,defines:m,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:h},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Ue(()=>Promise.resolve().then(()=>U5t),void 0),Ue(()=>Promise.resolve().then(()=>z5t),void 0)]):await Promise.all([Ue(()=>Promise.resolve().then(()=>B5t),void 0),Ue(()=>Promise.resolve().then(()=>k5t),void 0)])}},this.scene.getEngine()),m)}return f.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(pw._StencilReference),this._engine.setStencilFunctionReference(pw._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const r=this._engine.getAlphaMode(),n=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(r),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=n}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}pw._StencilReference=4;class K_e{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity===e||!this._hasVelocity()||(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!((e=this.vertexBuffers)!=null&&e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new Ae,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new J1({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new J1({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||e===0)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||e===0)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;(e=this._depthEffectWrapper)==null||e.dispose(!1),(t=this._thicknessEffectWrapper)==null||t.dispose(!1)}}class sqe extends K_e{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class Xne{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,this._blurPostProcesses!==null)){const t=this._blurPostProcesses[0],i=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let r=0;r{this._postProcessRunningIndex===0?g.setTexture("textureSampler",e):g._bindTexture("textureSampler",f.inputTexture.texture),g.setInt("filterSize",this.blurFilterSize),g.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),f.onSizeChangedObservable.add(()=>{f._textures.forEach(g=>{g.texture.wrapU=xe.CLAMP_ADDRESSMODE,g.texture.wrapV=xe.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const p=new Ft("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);p.samples=this._samples,p.onApplyObservable.add(g=>{g.setInt("filterSize",this.blurFilterSize),g.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(g=>{g.texture.wrapU=xe.CLAMP_ADDRESSMODE,g.texture.wrapV=xe.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p),f.autoClear=!1,p.autoClear=!1;const m=[];for(let g=0;g{this._postProcessRunningIndex===0?_.setTexture("textureSampler",e):_._bindTexture("textureSampler",p.inputTexture.texture),_.setInt("maxFilterSize",this.blurMaxFilterSize),_.setFloat2("blurDir",1/this._blurTextureSizeX,0),_.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),_.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(_=>{_.texture.wrapU=xe.CLAMP_ADDRESSMODE,_.texture.wrapV=xe.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p);const m=new Ft("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);m.samples=this._samples,m.onApplyObservable.add(_=>{_.setInt("maxFilterSize",this.blurMaxFilterSize),_.setFloat2("blurDir",0,1/this._blurTextureSizeY),_.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),_.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),m.onSizeChangedObservable.add(()=>{m._textures.forEach(_=>{_.texture.wrapU=xe.CLAMP_ADDRESSMODE,_.texture.wrapV=xe.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(m),p.autoClear=!1,m.autoClear=!1;const g=[];for(let _=0;_{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((((e=this._camera)==null?void 0:e.fov)??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),(e=this._rt)==null||e.dispose(),this._rt=null,(t=this._texture)==null||t.dispose(),this._texture=null,(i=this._rtBlur)==null||i.dispose(),this._rtBlur=null,(r=this._textureBlurred)==null||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var zde;(function(s){s[s.DepthTexture=0]="DepthTexture",s[s.DepthBlurredTexture=1]="DepthBlurredTexture",s[s.ThicknessTexture=2]="ThicknessTexture",s[s.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",s[s.DiffuseTexture=4]="DiffuseTexture",s[s.Normals=5]="Normals",s[s.DiffuseRendering=6]="DiffuseRendering"})(zde||(zde={}));class Vde{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Re(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new D(-2,-1,1).normalize(),this._debugFeature=1,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new Ae,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new he,this._depthClearColor=new Ze(1e6,1e6,1e6,1),this._thicknessClearColor=new Ze(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=this._depthMapSize!==null?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new Xne("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const n=this._diffuseMapSize??this._engine.getRenderWidth(),a=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new Xne("Diffuse",this._scene,n,a,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),r=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Xne("Thickness",this._scene,i,r,i,r,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(e===null||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(e===null||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],r=[];if(this.dispose(!0),!this._camera)return;const n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new we(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),r.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),r.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),r.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),r.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._compositeMode&&r.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(r.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===5?r.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===6?r.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(r.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),(this._debugFeature===0||this._debugFeature===1)&&r.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Ft("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(r.join(` `)),this._renderPostProcess.samples=this._samples;const o=e,l=o.setTextureSampler;this._renderPostProcess.onApplyObservable.add(c=>{var u,h,d,f,p,m,g,_,y,v;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),l&&l.call(o,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(c.setTexture("depthSampler",this._depthRenderTarget.textureBlur),l&&l.call(o,"depthSamplerSampler",((h=this._depthRenderTarget.textureBlur)==null?void 0:h.getInternalTexture())??null)):(c.setTexture("depthSampler",this._depthRenderTarget.texture),l&&l.call(o,"depthSamplerSampler",((u=this._depthRenderTarget.texture)==null?void 0:u.getInternalTexture())??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(c.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),l&&l.call(o,"diffuseSamplerSampler",((f=this._diffuseRenderTarget.textureBlur)==null?void 0:f.getInternalTexture())??null)):(c.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),l&&l.call(o,"diffuseSamplerSampler",((d=this._diffuseRenderTarget.texture)==null?void 0:d.getInternalTexture())??null)):c.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(c.setFloat("thickness",this.minimumThickness),c._bindTexture("bgDepthSampler",this._bgDepthTexture),l&&l.call(o,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(c.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),l&&l.call(o,"thicknessSamplerSampler",((m=this._thicknessRenderTarget.textureBlur)==null?void 0:m.getInternalTexture())??null)):(c.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),l&&l.call(o,"thicknessSamplerSampler",((p=this._thicknessRenderTarget.texture)==null?void 0:p.getInternalTexture())??null)),c.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const x=this._environmentMap??this._scene.environmentTexture;x&&(c.setTexture("reflectionSampler",x),l&&l.call(o,"reflectionSamplerSampler",(x==null?void 0:x.getInternalTexture())??null))}if(c.setMatrix("viewMatrix",this._scene.getViewMatrix()),c.setMatrix("invProjectionMatrix",this._invProjectionMatrix),c.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),c.setVector2("texelSize",a),c.setFloat("density",this.density),c.setFloat("refractionStrength",this.refractionStrength),c.setFloat("fresnelClamp",this.fresnelClamp),c.setFloat("specularPower",this.specularPower),c.setVector3("dirLight",this.dirLight),c.setFloat("cameraFar",this._camera.maxZ),this._debug){let x=null;switch(this._debugFeature){case 0:x=this._depthRenderTarget.texture;break;case 1:x=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case 2:x=((g=this._thicknessRenderTarget)==null?void 0:g.texture)??null;break;case 3:x=(_=this._thicknessRenderTarget)!=null&&_.enableBlur?((y=this._thicknessRenderTarget)==null?void 0:y.textureBlur)??null:((v=this._thicknessRenderTarget)==null?void 0:v.texture)??null;break;case 4:this._diffuseRenderTarget&&(x=this._diffuseRenderTarget.texture);break}this._debugFeature!==5&&(c.setTexture("debugSampler",x),l&&l.call(o,"debugSamplerSampler",(x==null?void 0:x.getInternalTexture())??null))}})}_clearTargets(){var e,t,i;(e=this._depthRenderTarget)!=null&&e.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(t=this._diffuseRenderTarget)!=null&&t.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(i=this._thicknessRenderTarget)!=null&&i.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var i,r,n,a,o,l;if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(i=this._depthRenderTarget)!=null&&i.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(r=this._diffuseRenderTarget)!=null&&r.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(n=this._thicknessRenderTarget)!=null&&n.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(a=this._depthRenderTarget)==null||a.applyBlurPostProcesses(),(o=this._diffuseRenderTarget)==null||o.applyBlurPostProcesses(),(l=this._thicknessRenderTarget)==null||l.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){var t,i,r,n;e||((t=this._depthRenderTarget)==null||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)==null||i.dispose(),this._diffuseRenderTarget=null,(r=this._thicknessRenderTarget)==null||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(n=this._renderPostProcess)==null||n.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class nqe extends K_e{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1;break}this._vertexBuffers[t]=new $(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new J1({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:t,uniformNames:e,samplerNames:[]})}isReady(){var e;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new $(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(((e=this._diffuseEffectWrapper)==null?void 0:e.effect.isReady())??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||e===0)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),this._particleSize!==null&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;super.dispose(),(e=this._diffuseEffectWrapper)==null||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}var Gde;(function(s){s[s.None=0]="None",s[s.ToLinearSpace=1]="ToLinearSpace",s[s.ToGammaSpace=2]="ToGammaSpace"})(Gde||(Gde={}));class aqe{get shaderLanguage(){return this._shaderLanguage}_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._shaderLanguage=0,this._shadersLoaded=!1,this._engine=e,this._isDepthTexture=t,this._renderer=new Pz(e),this._initShaderSourceAsync(t)}async _initShaderSourceAsync(e){const t=this._engine;t.isWebGPU?(this._shaderLanguage=1,await Ue(()=>Promise.resolve().then(()=>APt),void 0)):await Ue(()=>Promise.resolve().then(()=>xPt),void 0),this._shadersLoaded=!0,this._effectWrapper=new J1({engine:t,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:e?["#define DEPTH_TEXTURE"]:[],shaderLanguage:this._shaderLanguage}),this._effectWrapper.onApplyObservable.add(()=>{e&&(t.setState(!1),t.setDepthBuffer(!0),t.depthCullingState.depthMask=!0,t.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._shadersLoaded&&this._effectWrapper.effect.isReady()}copy(e,t,i=0){if(!this.isReady())return!1;this._source=e,this._conversion=i;const r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class zIt{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new aqe(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"});const n=this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil");n.label=`FluidDepthTextureCopy${t}x${i}x${r}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const VIt="fluidRenderingParticleDepthVertexShader",GIt=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; #ifdef FLUIDRENDERING_VELOCITY attribute vec3 velocity;varying float velocityNorm; #endif void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; #ifdef FLUIDRENDERING_VELOCITY velocityNorm=length(velocity); #endif } `;de.ShadersStore[VIt]=GIt;const WIt="fluidRenderingParticleDepthPixelShader",KIt=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; #ifdef FLUIDRENDERING_VELOCITY varying float velocityNorm; #endif void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); #ifndef FLUIDRENDERING_RHS normal.z=-normal.z; #endif vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; #ifdef WEBGPU gl_FragDepth=clipSpacePos.z/clipSpacePos.w; #else gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; #endif #ifdef FLUIDRENDERING_RHS realViewPos.z=-realViewPos.z; #endif #ifdef FLUIDRENDERING_VELOCITY glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); #else glFragColor=vec4(realViewPos.z,0.,0.,1.); #endif } `;de.ShadersStore[WIt]=KIt;const HIt="fluidRenderingParticleThicknessVertexShader",jIt=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} `;de.ShadersStore[HIt]=jIt;const XIt="fluidRenderingParticleThicknessPixelShader",YIt=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} `;de.ShadersStore[XIt]=YIt;const QIt="fluidRenderingParticleDiffuseVertexShader",$It=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} `;de.ShadersStore[QIt]=$It;const ZIt="fluidRenderingParticleDiffusePixelShader",qIt=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} `;de.ShadersStore[ZIt]=qIt;const JIt="fluidRenderingBilateralBlurPixelShader",e5t=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} `;de.ShadersStore[JIt]=e5t;const t5t="fluidRenderingStandardBlurPixelShader",i5t=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} sum/=wsum;glFragColor=vec4(sum.rgb,1.);} `;de.ShadersStore[t5t]=i5t;const r5t="fluidRenderingRenderPixelShader",s5t=`#define DISABLE_UNIFORMITY_ANALYSIS #define IOR 1.333 #define ETA 1.0/IOR #define F0 0.02 uniform sampler2D textureSampler;uniform sampler2D depthSampler; #ifdef FLUIDRENDERING_DIFFUSETEXTURE uniform sampler2D diffuseSampler; #else uniform vec3 diffuseColor; #endif #ifdef FLUIDRENDERING_FIXED_THICKNESS uniform float thickness;uniform sampler2D bgDepthSampler; #else uniform float minimumThickness;uniform sampler2D thicknessSampler; #endif #ifdef FLUIDRENDERING_ENVIRONMENT uniform samplerCube reflectionSampler; #endif #if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) uniform sampler2D debugSampler; #endif uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; #ifdef FLUIDRENDERING_RHS ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; #else ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; #endif ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} void main(void) {vec2 texCoord=vUV; #if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) vec4 color=texture2D(debugSampler,texCoord); #ifdef FLUIDRENDERING_DEBUG_DEPTH glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} #else glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} #endif return; #endif vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; #ifndef FLUIDRENDERING_FIXED_THICKNESS float thickness=texture2D(thicknessSampler,texCoord).x; #else float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; #endif vec4 backColor=texture2D(textureSampler,texCoord); #ifndef FLUIDRENDERING_FIXED_THICKNESS if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { #else if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { #endif #ifdef FLUIDRENDERING_COMPOSITE_MODE glFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a; #else glFragColor=backColor; #endif return;} vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} vec3 normal=normalize(cross(ddy,ddx)); #ifdef FLUIDRENDERING_RHS normal=-normal; #endif #ifndef WEBGPU if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} #endif #if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) glFragColor=vec4(normal*0.5+0.5,1.0);return; #endif vec3 rayDir=normalize(viewPos); #ifdef FLUIDRENDERING_DIFFUSETEXTURE vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; #endif vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); #ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; #endif vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0); #ifdef FLUIDRENDERING_COMPOSITE_MODE if (transmitted.a==0.) transmitted.a=thickness; #endif vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); vec3 refractionColor=transmitted.rgb*transmittance; #ifdef FLUIDRENDERING_ENVIRONMENT vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; #else vec3 finalColor=refractionColor+specular; #endif #ifdef FLUIDRENDERING_VELOCITY float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); #endif glFragColor=vec4(finalColor,transmitted.a);} `;de.ShadersStore[r5t]=s5t;Object.defineProperty(gt.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(s){this._fluidRenderer=s},enumerable:!0,configurable:!0});gt.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new Hee(this),this._fluidRenderer)};gt.prototype.disableFluidRenderer=function(){var s;(s=this._fluidRenderer)==null||s.dispose(),this._fluidRenderer=null};function n5t(s){return!!s.particleSystem}function a5t(s){return!!s.addBuffers}class oqe{constructor(e){this.name=ot.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ot.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ot.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;(t=this.scene.fluidRenderer)==null||t._prepareRendering()}_afterCameraDraw(e){var t;(t=this.scene.fluidRenderer)==null||t._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{i._rebuild()})}dispose(){this.scene.disableFluidRenderer()}}class Hee{static _SceneComponentInitialization(e){let t=e._getComponent(ot.NAME_FLUIDRENDERER);t||(t=new oqe(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,Hee._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return t!==-1?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){const n=new sqe(this._scene,e);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new Vde(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),t!==void 0&&(i.generateDiffuseTexture=t);const a={object:n,targetRenderer:i};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}addCustomParticles(e,t,i,r,n){const a=new nqe(this._scene,e,t);a.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new Vde(this._scene,n),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(r.generateDiffuseTexture=i);const o={object:a,targetRenderer:r};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return i===-1?!1:(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){const e={};for(let r=0;r{var c;a.inputTexture.depthStencilTexture||a.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,o[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${a.name}`);for(const u of o){const h=(c=u._thicknessRenderTarget)==null?void 0:c.renderTarget,d=h==null?void 0:h.texture;if(h&&d){const f=d.width+"_"+d.height;let p=l[f];p||(p=l[f]=new zIt(this._engine,d.width,d.height)),p.depthRTWrapper.shareDepth(h)}}})}t=this._cameras.keys();for(let i=t.next();i.done!==!0;i=t.next()){const r=i.value,a=this._cameras.get(r)[1],o=e.get(r);if(o)for(const l in a)o[1][l]||a[l].dispose();else for(const l in a)a[l].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{i._depthRenderTarget&&(i._depthRenderTarget.particleSize=t)})}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var i;for(let r=0;r{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class o5t{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=he.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t==null||t.forEach(i=>{this._addMeshToMRT(i)})}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach(t=>{this._addMeshToMRT(t)}),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,r=t.rg11b10ufColorRenderable?4:5;this._mrt=new nv("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,r]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new Ze(0,0,0,1),this._mrt.noPrePassRenderer=!0;let n,a;const o=this._scene.getEngine().supportsUniformBuffers;o&&(n=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`));let l;this._mrt.onBeforeBindObservable.add(()=>{a=this._scene.getSceneUniformBuffer(),l=this._light.shadowEnabled,this._light.shadowEnabled=!1}),this._mrt.onBeforeRenderObservable.add(c=>{n&&this._scene.setSceneUniformBuffer(n);const u=this._light.getViewMatrix(c),h=this._light.getProjectionMatrix(u||void 0,this._mrt.renderList||void 0);u&&h&&this._scene.setTransformMatrix(u,h),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._mrt.onAfterUnbindObservable.add(()=>{var c;n&&this._scene.setSceneUniformBuffer(a),this._scene.updateTransformMatrix(),this._light.shadowEnabled=l,this._counters[0].value=((c=this._mrt.renderTarget.gpuTimeInFrame)==null?void 0:c.counter.lastSecAverage)??0}),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?t===-1&&this._scene.customRenderTargets.push(this._mrt):t!==-1&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){var r;(r=this._mrt.renderList)==null||r.push(e);const t=e.material;if(e.getTotalVertices()===0||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const n=new Xx(i);n.isEnabled=!0,n.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class l5t extends _s{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class Xx extends fu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,Xx.Name,300,new l5t),this._lightColor=new Re,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Pr?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===Zi.LIGHTTYPEID_SPOTLIGHT;if(t){const i=this.light;this._hasProjectionTexture=i.projectionTexture?i.projectionTexture.isReady():!1}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t,e.SCENE_MRT_COUNT=3}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:`#ifdef RSMCREATE uniform mat4 rsmTextureProjectionMatrix; uniform vec4 rsmSpotInfo; uniform vec3 rsmLightColor; uniform vec3 rsmLightPosition; #endif`}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===Zi.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=se.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(t.angle*.5))}}getCustomCode(e,t){return e==="vertex"?null:t===1?{CUSTOM_FRAGMENT_DEFINITIONS:` #ifdef RSMCREATE #ifdef RSMCREATE_PROJTEXTURE var rsmTextureProjectionSamplerSampler: sampler; var rsmTextureProjectionSampler: texture_2d; #endif #endif `,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:` #ifdef RSMCREATE var rsmColor = ${this._varAlbedoName} * uniforms.rsmLightColor; #ifdef RSMCREATE_PROJTEXTURE { var strq = uniforms.rsmTextureProjectionMatrix * vec4f(fragmentInputs.vPositionW, 1.0); strq /= strq.w; rsmColor *= textureSample(rsmTextureProjectionSampler, rsmTextureProjectionSamplerSampler, strq.xy).rgb; } #endif #ifdef RSMCREATE_LIGHT_IS_SPOT { var cosAngle = max(0., dot(uniforms.rsmSpotInfo.xyz, normalize(fragmentInputs.vPositionW - uniforms.rsmLightPosition))); rsmColor = sign(cosAngle - uniforms.rsmSpotInfo.w) * rsmColor; } #endif #define MRT_AND_COLOR fragmentOutputs.fragData0 = vec4f(fragmentInputs.vPositionW, 1.); fragmentOutputs.fragData1 = vec4f(normalize(normalW) * 0.5 + 0.5, 1.); fragmentOutputs.fragData2 = vec4f(rsmColor, 1.); #endif `}:{CUSTOM_FRAGMENT_BEGIN:` #ifdef RSMCREATE #extension GL_EXT_draw_buffers : require #endif `,CUSTOM_FRAGMENT_DEFINITIONS:` #ifdef RSMCREATE #ifdef RSMCREATE_PROJTEXTURE uniform highp sampler2D rsmTextureProjectionSampler; #endif layout(location = 0) out highp vec4 glFragData[3]; vec4 glFragColor; #endif `,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:` #ifdef RSMCREATE vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor; #ifdef RSMCREATE_PROJTEXTURE { vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0); strq /= strq.w; rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb; } #endif #ifdef RSMCREATE_LIGHT_IS_SPOT { float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition))); rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor; } #endif glFragData[0] = vec4(vPositionW, 1.); glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.); glFragData[2] = vec4(rsmColor, 1.); #endif `}}}Xx.Name="RSMCreate";F([X()],Xx.prototype,"light",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Xx.prototype,"isEnabled",void 0);ve("BABYLON.RSMCreatePluginMaterial",Xx);class c5t{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}class jee{get enable(){return this._enable}set enable(e){this._giRSM.length===0&&(e=!1),e!==this._enable&&(this._enable=e,this._debugLayer.isEnabled=this._showOnlyGI&&e,this._materialsWithRenderPlugin.forEach(t=>{if(t.pluginManager){const i=t.pluginManager.getPlugin(Kf.Name);i.isEnabled=e}}),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get shaderLanguage(){return this._shaderLanguage}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{t.getTotalVertices()>0&&t.isEnabled()&&t.material&&this._addGISupportToMaterial(t.material)})}get countersGPU(){return this._counters}recreateResources(e=!1){if(!this._shadersLoaded){this._onShaderLoadedObservable.addOnce(()=>{this.recreateResources(e)});return}this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){var i;(i=this._sampleTexture)==null||i.dispose(),this._maxSamples=e;const t=new Float32Array(this._maxSamples*4);for(let r=0;r{var l,c;const a=this._engine._currentRenderTarget;let o=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),o=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let u=0;uPromise.resolve().then(()=>m5t),void 0),Ue(()=>Promise.resolve().then(()=>g5t),void 0),Ue(()=>Promise.resolve().then(()=>_5t),void 0),Ue(()=>Promise.resolve().then(()=>v5t),void 0)])):await Promise.all([Ue(()=>Promise.resolve().then(()=>h5t),void 0),Ue(()=>Promise.resolve().then(()=>d5t),void 0),Ue(()=>Promise.resolve().then(()=>f5t),void 0),Ue(()=>Promise.resolve().then(()=>p5t),void 0)]),this._shadersLoaded=!0,this._onShaderLoadedObservable.notifyObservers()}_disposePostProcesses(e=!1){var t,i,r,n,a;(t=this._blurRTT)==null||t.dispose(),this._blurRTT=null,this._blurPostProcesses=[],(i=this._blurXPostprocess)==null||i.dispose(),this._blurXPostprocess=null,(r=this._blurYPostprocess)==null||r.dispose(),this._blurYPostprocess=null,(n=this._upsamplingXPostprocess)==null||n.dispose(),this._upsamplingXPostprocess=null,(a=this._upsamplingYPostprocess)==null||a.dispose(),this._upsamplingYPostprocess=null;for(const o of this._ppGlobalIllumination)o.dispose();this._ppGlobalIllumination=[],e&&(this._geomBufferEnabled?(this._scene.enableGeometryBufferRenderer(),this._scene.geometryBufferRenderer.enablePosition=this._geomBufferEnablePosition):this._scene.disableGeometryBufferRenderer()),this._counters=[],this._countersRTW=[]}_setPluginParameters(){this._enable&&this._materialsWithRenderPlugin.forEach(e=>{if(e.pluginManager){const t=e.pluginManager.getPlugin(Kf.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}})}_createPostProcesses(){var a,o;if(!this._enable)return;const e=this._giTextureType===13?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=((a=this._scene.geometryBufferRenderer)==null?void 0:a.enablePosition)??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,jee.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,r=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let n="";i&&(n+=`#define DECODE_NORMAL `),r||(n+=`#define TRANSFORM_NORMAL `);for(let l=0;l{d.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.POSITION_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.NORMAL_TEXTURE_TYPE)]),d.setTexture("rsmPositionW",u.positionWorldTexture),d.setTexture("rsmNormalW",u.normalWorldTexture),d.setTexture("rsmFlux",u.fluxTexture),d.setMatrix("rsmLightMatrix",u.lightTransformationMatrix),c.useFullTexture?d.setFloat4("rsmInfo",u.fluxTexture.getInternalTexture().width,u.fluxTexture.getInternalTexture().height,c.intensity,c.edgeArtifactCorrection):(d.setTexture("rsmSamples",this._sampleTexture),d.setFloat4("rsmInfo",c.numSamples,c.radius,c.intensity,c.edgeArtifactCorrection),d.setFloat4("rsmInfo2",c.noiseFactor,c.rotateSample?1:0,u.fluxTexture.getInternalTexture().width,u.fluxTexture.getInternalTexture().height)),r||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),d.setMatrix("invView",this._tempMatrix))})}for(const l of this._ppGlobalIllumination)l.inputTexture||l.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const l=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new Rs("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const c=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(c),this._blurXPostprocess=new Ft(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:l,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._blurXPostprocess.onApplyObservable.add(h=>{h._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),h.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.DEPTH_TEXTURE_TYPE)]),h.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.NORMAL_TEXTURE_TYPE)]),h.setInt("filterSize",this.blurKernel),h.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),h.setFloat("depthThreshold",this.blurDepthThreshold),h.setFloat("normalThreshold",this.blurNormalThreshold)}),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new Ft("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:l,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add(h=>{h.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.DEPTH_TEXTURE_TYPE)]),h.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.NORMAL_TEXTURE_TYPE)]),h.setInt("filterSize",this.blurKernel),h.setFloat2("blurDir",0,1/this._giTextureDimensions.height),h.setFloat("depthThreshold",this.blurDepthThreshold),h.setFloat("normalThreshold",this.blurNormalThreshold)}),this._blurYPostprocess.resize(l.width,l.height),c.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),!(this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height)&&!this._forceFullSizeBlur){const h=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(h),this._upsamplingXPostprocess=new Ft(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:l,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add(d=>{d.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.DEPTH_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.NORMAL_TEXTURE_TYPE)]),d.setInt("filterSize",this.upsamplerKernel),d.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),d.setFloat("depthThreshold",this.blurDepthThreshold),d.setFloat("normalThreshold",this.blurNormalThreshold)}),this._upsamplingXPostprocess.resize(l.width,l.height),c.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new Ft("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add(d=>{d.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.DEPTH_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(Nr.NORMAL_TEXTURE_TYPE)]),d.setInt("filterSize",this.upsamplerKernel),d.setFloat2("blurDir",0,1/this._outputDimensions.height),d.setFloat("depthThreshold",this.blurDepthThreshold),d.setFloat("normalThreshold",this.blurNormalThreshold)}),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),h.push(this._upsamplingYPostprocess.inputTexture)),h.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}else c.push(this._blurRTT.renderTarget)}(o=this._debugLayer.texture)==null||o.dispose(),this._debugLayer.texture=new $r(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){var i;if((i=e.pluginManager)!=null&&i.getPlugin(Kf.Name))return;const t=new Kf(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}jee.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class u5t extends _s{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class Kf extends fu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,Kf.Name,310,new u5t),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Pr}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:`#ifdef RENDER_WITH_GIRSM uniform vec2 girsmTextureOutputSize; #endif`}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e,t){let i;return t===1?(i={CUSTOM_FRAGMENT_DEFINITIONS:` #ifdef RENDER_WITH_GIRSM var girsmTextureGIContribSampler: sampler; var girsmTextureGIContrib: texture_2d; fn computeIndirect() -> vec3f { var uv = fragmentInputs.position.xy / uniforms.girsmTextureOutputSize; return textureSample(girsmTextureGIContrib, girsmTextureGIContribSampler, uv).rgb; } #endif `,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:` #ifdef RENDER_WITH_GIRSM finalDiffuse += computeIndirect() * surfaceAlbedo.rgb; #endif `},this._isPBR||(i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR=` #ifdef RENDER_WITH_GIRSM color = vec4f(color.rgb + computeIndirect() * baseColor.rgb, color.a); #endif `)):(i={CUSTOM_FRAGMENT_DEFINITIONS:` #ifdef RENDER_WITH_GIRSM uniform sampler2D girsmTextureGIContrib; vec3 computeIndirect() { vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize; return texture2D(girsmTextureGIContrib, uv).rgb; } #endif `,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:` #ifdef RENDER_WITH_GIRSM finalDiffuse += computeIndirect() * surfaceAlbedo.rgb; #endif `},this._isPBR||(i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR=` #ifdef RENDER_WITH_GIRSM color.rgb += computeIndirect() * baseColor.rgb; #endif `)),e==="vertex"?null:i}}Kf.Name="GIRSMRender";F([X()],Kf.prototype,"textureGIContrib",void 0);F([X()],Kf.prototype,"outputTextureWidth",void 0);F([X()],Kf.prototype,"outputTextureHeight",void 0);F([X(),Fe("_markAllSubMeshesAsTexturesDirty")],Kf.prototype,"isEnabled",void 0);ve("BABYLON.GIRSMRenderPluginMaterial",Kf);const lqe="bilateralBlurPixelShader",cqe=`uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;} vec3 normal=textureLod(normalSampler,vUV,0.).rgb; #ifdef DECODE_NORMAL normal=normal*2.0-1.0; #endif float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb; #ifdef DECODE_NORMAL sampleNormal=sampleNormal*2.0-1.0; #endif float r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;} glFragColor=vec4(sum/wsum,1.);} `;de.ShadersStore[lqe]=cqe;const uqe={name:lqe,shader:cqe},h5t=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurPixelShader:uqe},Symbol.toStringTag,{value:"Module"})),hqe="bilateralBlurQualityPixelShader",dqe=`uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;} vec3 normal=textureLod(normalSampler,vUV,0.).rgb; #ifdef DECODE_NORMAL normal=normal*2.0-1.0; #endif float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb; #ifdef DECODE_NORMAL sampleNormal=sampleNormal*2.0-1.0; #endif float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}} glFragColor=vec4(sum/wsum,1.);} `;de.ShadersStore[hqe]=dqe;const fqe={name:hqe,shader:dqe},d5t=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurQualityPixelShader:fqe},Symbol.toStringTag,{value:"Module"})),pqe="rsmGlobalIlluminationPixelShader",mqe=`/** * The implementation is an application of the formula found in http: * For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts). */ precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples; #ifdef TRANSFORM_NORMAL uniform mat4 invView; #endif float mod289(float x){return x-floor(x*(1.0/289.0))*289.0;} vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;} vec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);} float noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);} vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);} return clamp(indirectDiffuse*intensity,0.0,1.0);} void main(void) {vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz; #ifdef DECODE_NORMAL normalW=normalW*2.0-1.0; #endif #ifdef TRANSFORM_NORMAL normalW=(invView*vec4(normalW,0.)).xyz; #endif gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;} `;de.ShadersStore[pqe]=mqe;const gqe={name:pqe,shader:mqe},f5t=Object.freeze(Object.defineProperty({__proto__:null,rsmGlobalIlluminationPixelShader:gqe},Symbol.toStringTag,{value:"Module"})),_qe="rsmFullGlobalIlluminationPixelShader",vqe=`/** * The implementation is a direct application of the formula found in http: */ precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux; #ifdef TRANSFORM_NORMAL uniform mat4 invView; #endif vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;} var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb; #ifdef DECODE_NORMAL normal=normal*2.0-1.0; #endif var sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords=vec2f(f32(x));var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb; #ifdef DECODE_NORMAL sampleNormal=sampleNormal*2.0-1.0; #endif var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var depthDelta: f32=abs(sampleDepth-depth);var wd: f32=step(depthDelta,uniforms.depthThreshold);var normalDelta: vec3f=abs(sampleNormal-normal);var wn: f32=step(normalDelta.x+normalDelta.y+normalDelta.z,uniforms.normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;} fragmentOutputs.color= vec4f(sum/wsum,1.);} `;de.ShadersStoreWGSL[xqe]=Aqe;const bqe={name:xqe,shader:Aqe},m5t=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurPixelShaderWGSL:bqe},Symbol.toStringTag,{value:"Module"})),Cqe="bilateralBlurQualityPixelShader",Sqe=`var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;} var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb; #ifdef DECODE_NORMAL normal=normal*2.0-1.0; #endif var sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {for (var y: i32=-uniforms.filterSize; y<=uniforms.filterSize; y++) {var coords: vec2f= vec2f(x,y)*uniforms.blurDir;var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords,0.).rgb; #ifdef DECODE_NORMAL sampleNormal=sampleNormal*2.0-1.0; #endif var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepth-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);var rNormal: f32=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);var wn: f32=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}} fragmentOutputs.color= vec4f(sum/wsum,1.);} `;de.ShadersStoreWGSL[Cqe]=Sqe;const Eqe={name:Cqe,shader:Sqe},g5t=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurQualityPixelShaderWGSL:Eqe},Symbol.toStringTag,{value:"Module"})),Tqe="rsmGlobalIlluminationPixelShader",Mqe=`/** * The implementation is an application of the formula found in http: * For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts). */ varying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;uniform rsmInfo2: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionWSampler: sampler;var rsmPositionW: texture_2d;var rsmNormalWSampler: sampler;var rsmNormalW: texture_2d;var rsmFluxSampler: sampler;var rsmFlux: texture_2d;var rsmSamples: texture_2d; #ifdef TRANSFORM_NORMAL uniform invView: mat4x4f; #endif fn mod289(x: f32)->f32{return x-floor(x*(1.0/289.0))*289.0;} fn mod289Vec4(x: vec4f)->vec4f {return x-floor(x*(1.0/289.0))* 289.0;} fn perm(x: vec4f)->vec4f {return mod289Vec4(((x*34.0)+1.0)*x) ;} fn noise(p: vec3f)->f32{var a: vec3f=floor(p);var d: vec3f=p-a;d=d*d*(3.0-2.0*d);var b: vec4f=a.xxyy+ vec4f(0.0,1.0,0.0,1.0);var k1: vec4f=perm(b.xyxy);var k2: vec4f=perm(k1.xyxy+b.zzww);var c: vec4f=k2+a.zzzz;var k3: vec4f=perm(c);var k4: vec4f=perm(c+1.0);var o1: vec4f=fract(k3*(1.0/41.0));var o2: vec4f=fract(k4*(1.0/41.0));var o3: vec4f=o2*d.z+o1*(1.0-d.z);var o4: vec2f=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);} fn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var numSamples: i32= i32(uniforms.rsmInfo.x);var radius: f32=uniforms.rsmInfo.y;var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var angle: f32=noise(p*uniforms.rsmInfo2.x);var c: f32=cos(angle);var s: f32=sin(angle);for (var i: i32=0; i(i,0),0).xyz;var weightSquare: f32=rsmSample.z;if (uniforms.rsmInfo2.y==1.0){rsmSample=vec3f(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c,rsmSample.z);} var uv: vec2f=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) {continue;} var vplPositionW: vec3f=textureSampleLevel(rsmPositionW,rsmPositionWSampler,uv,0.).xyz;var vplNormalW: vec3f=textureSampleLevel(rsmNormalW,rsmNormalWSampler,uv,0.).xyz*2.0-1.0;var vplFlux: vec3f=textureSampleLevel(rsmFlux,rsmFluxSampler,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; var dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);} return clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));} @fragment fn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,input.vUV).xyz; #ifdef DECODE_NORMAL normalW=normalW*2.0-1.0; #endif #ifdef TRANSFORM_NORMAL normalW=(uniforms.invView* vec4f(normalW,0.)).xyz; #endif fragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);} `;de.ShadersStoreWGSL[Tqe]=Mqe;const Rqe={name:Tqe,shader:Mqe},_5t=Object.freeze(Object.defineProperty({__proto__:null,rsmGlobalIlluminationPixelShaderWGSL:Rqe},Symbol.toStringTag,{value:"Module"})),Iqe="rsmFullGlobalIlluminationPixelShader",Pqe=`/** * The implementation is a direct application of the formula found in http: */ varying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionW: texture_2d;var rsmNormalW: texture_2d;var rsmFlux: texture_2d; #ifdef TRANSFORM_NORMAL uniform invView: mat4x4f; #endif fn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var width: i32= i32(uniforms.rsmInfo.x);var height: i32= i32(uniforms.rsmInfo.y);for (var j: i32=0; j(i,j);var vplPositionW: vec3f=textureLoad(rsmPositionW,uv,0).xyz;var vplNormalW: vec3f=textureLoad(rsmNormalW,uv,0).xyz*2.0-1.0;var vplFlux: vec3f=textureLoad(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; var dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}} return clamp(indirectDiffuse*intensity,0.0,1.0);} @fragment fn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,fragmentInputs.vUV).xyz; #ifdef DECODE_NORMAL normalW=normalW*2.0-1.0; #endif #ifdef TRANSFORM_NORMAL normalW=(uniforms.invView* vec4f(normalW,0.)).xyz; #endif fragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);} `;de.ShadersStoreWGSL[Iqe]=Pqe;const wqe={name:Iqe,shader:Pqe},v5t=Object.freeze(Object.defineProperty({__proto__:null,rsmFullGlobalIlluminationPixelShaderWGSL:wqe},Symbol.toStringTag,{value:"Module"})),Dqe="depthPixelShader",Lqe=`#ifdef ALPHATEST varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include varying vDepthMetric: f32; #ifdef PACKED #include #endif #ifdef STORE_CAMERASPACE_Z varying vViewPos: vec4f; #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include #ifdef ALPHATEST if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;} #endif #ifdef STORE_CAMERASPACE_Z #ifdef PACKED fragmentOutputs.color=pack(input.vViewPos.z); #else fragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0); #endif #else #ifdef NONLINEARDEPTH #ifdef PACKED fragmentOutputs.color=pack(input.position.z); #else fragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0); #endif #else #ifdef PACKED fragmentOutputs.color=pack(input.vDepthMetric); #else fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0); #endif #endif #endif }`;de.ShadersStoreWGSL[Dqe]=Lqe;const Oqe={name:Dqe,shader:Lqe},y5t=Object.freeze(Object.defineProperty({__proto__:null,depthPixelShaderWGSL:Oqe},Symbol.toStringTag,{value:"Module"})),Nqe="depthVertexShader",Fqe=`attribute position: vec3f; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform viewProjection: mat4x4f;uniform depthValues: vec2f; #if defined(ALPHATEST) || defined(NEED_UV) varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #ifdef STORE_CAMERASPACE_Z uniform view: mat4x4f;varying vViewPos: vec4f; #endif varying vDepthMetric: f32; #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); #include vertexOutputs.position=uniforms.viewProjection*worldPos; #ifdef STORE_CAMERASPACE_Z vertexOutputs.vViewPos=uniforms.view*worldPos; #else #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y)); #else vertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y)); #endif #endif #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef UV2 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #endif } `;de.ShadersStoreWGSL[Nqe]=Fqe;const Bqe={name:Nqe,shader:Fqe},x5t=Object.freeze(Object.defineProperty({__proto__:null,depthVertexShaderWGSL:Bqe},Symbol.toStringTag,{value:"Module"})),kqe="geometryPixelShader",Uqe=`#ifdef BUMP varying vWorldView: mat4x4f;varying vNormalW: vec3f; #else varying vNormalV: vec3f; #endif varying vViewPos: vec4f; #if defined(POSITION) || defined(BUMP) varying vPositionW: vec3f; #endif #ifdef VELOCITY varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #ifdef NEED_UV varying vUV: vec2f; #endif #ifdef BUMP uniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f; #endif #if defined(REFLECTIVITY) #if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;varying vReflectivityUV: vec2f; #endif #ifdef ALBEDOTEXTURE varying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d; #endif #ifdef REFLECTIVITYCOLOR uniform reflectivityColor: vec3f; #endif #ifdef ALBEDOCOLOR uniform albedoColor: vec3f; #endif #ifdef METALLIC uniform metallic: f32; #endif #if defined(ROUGHNESS) || defined(GLOSSINESS) uniform glossiness: f32; #endif #endif #if defined(ALPHATEST) && defined(NEED_UV) var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include #include #include #include @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include #ifdef ALPHATEST if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;} #endif var normalOutput: vec3f; #ifdef BUMP var normalW: vec3f=normalize(input.vNormalW); #include #ifdef NORMAL_WORLDSPACE normalOutput=normalW; #else normalOutput=normalize( vec3f(input.vWorldView* vec4f(normalW,0.0))); #endif #else normalOutput=normalize(input.vNormalV); #endif #ifdef ENCODE_NORMAL normalOutput=normalOutput*0.5+0.5; #endif var fragData: array,SCENE_MRT_COUNT>; #ifdef PREPASS #ifdef PREPASS_DEPTH fragData[DEPTH_INDEX]= vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0); #endif #ifdef PREPASS_NORMAL fragData[NORMAL_INDEX]= vec4f(normalOutput,1.0); #endif #else fragData[0]= vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0);fragData[1]= vec4f(normalOutput,1.0); #endif #ifdef POSITION fragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0); #endif #ifdef VELOCITY var a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0); #endif #ifdef REFLECTIVITY var reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0); #ifdef METALLICWORKFLOW var metal: f32=1.0;var roughness: f32=1.0; #ifdef ORMTEXTURE metal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g; #endif #ifdef METALLIC metal*=uniforms.metallic; #endif #ifdef ROUGHNESS roughness*=(1.0-uniforms.glossiness); #endif reflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0); #ifdef ALBEDOTEXTURE color=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb; #ifdef GAMMAALBEDO color=toLinearSpaceVec4(color); #endif #endif #ifdef ALBEDOCOLOR color*=uniforms.albedoColor.xyz; #endif reflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a); #else #if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) reflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV); #ifdef GAMMAREFLECTIVITYTEXTURE reflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a); #endif #else #ifdef REFLECTIVITYCOLOR reflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0); #endif #endif #ifdef GLOSSINESSS reflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness); #endif #endif fragData[REFLECTIVITY_INDEX]=reflectivity; #endif #if SCENE_MRT_COUNT>0 fragmentOutputs.fragData0=fragData[0]; #endif #if SCENE_MRT_COUNT>1 fragmentOutputs.fragData1=fragData[1]; #endif #if SCENE_MRT_COUNT>2 fragmentOutputs.fragData2=fragData[2]; #endif #if SCENE_MRT_COUNT>3 fragmentOutputs.fragData3=fragData[3]; #endif #if SCENE_MRT_COUNT>4 fragmentOutputs.fragData4=fragData[4]; #endif #if SCENE_MRT_COUNT>5 fragmentOutputs.fragData5=fragData[5]; #endif #if SCENE_MRT_COUNT>6 fragmentOutputs.fragData6=fragData[6]; #endif #if SCENE_MRT_COUNT>7 fragmentOutputs.fragData7=fragData[7]; #endif } `;de.ShadersStoreWGSL[kqe]=Uqe;const zqe={name:kqe,shader:Uqe},A5t=Object.freeze(Object.defineProperty({__proto__:null,geometryPixelShaderWGSL:zqe},Symbol.toStringTag,{value:"Module"})),Vqe="geometryVertexShader",Gqe=`#include #include #include #include[0..maxSimultaneousMorphTargets] #include #include #include attribute position: vec3f;attribute normal: vec3f; #ifdef NEED_UV varying vUV: vec2f; #ifdef ALPHATEST uniform diffuseMatrix: mat4x4f; #endif #ifdef BUMP uniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f; #endif #ifdef REFLECTIVITY uniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f; #endif #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #ifdef BUMP varying vWorldView: mat4x4f; #endif #ifdef BUMP varying vNormalW: vec3f; #else varying vNormalV: vec3f; #endif varying vViewPos: vec4f; #if defined(POSITION) || defined(BUMP) varying vPositionW: vec3f; #endif #ifdef VELOCITY uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #include #include[0..maxSimultaneousMorphTargets] #include #if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #include #include var worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0)); #ifdef BUMP vertexOutputs.vWorldView=scene.view*finalWorld;vertexOutputs.vNormalW=normalUpdated; #else #ifdef NORMAL_WORLDSPACE vertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz); #else vertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz); #endif #endif vertexOutputs.vViewPos=scene.view*worldPos; #if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0); #if NUM_BONE_INFLUENCERS>0 var previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0); #else vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #endif #if defined(POSITION) || defined(BUMP) vertexOutputs.vPositionW=worldPos.xyz/worldPos.w; #endif vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0); #include #ifdef NEED_UV #ifdef UV1 #if defined(ALPHATEST) && defined(ALPHATEST_UV1) vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #else vertexOutputs.vUV=input.uv; #endif #ifdef BUMP_UV1 vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef REFLECTIVITY_UV1 vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef ALBEDO_UV1 vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #endif #ifdef UV2 #if defined(ALPHATEST) && defined(ALPHATEST_UV2) vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy; #else vertexOutputs.vUV=input.uv2; #endif #ifdef BUMP_UV2 vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #ifdef REFLECTIVITY_UV2 vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #ifdef ALBEDO_UV2 vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(input.uv2,1.0,0.0)).xy; #endif #endif #endif #include } `;de.ShadersStoreWGSL[Vqe]=Gqe;const Wqe={name:Vqe,shader:Gqe},b5t=Object.freeze(Object.defineProperty({__proto__:null,geometryVertexShaderWGSL:Wqe},Symbol.toStringTag,{value:"Module"})),C5t="boundingBoxRendererFragmentDeclaration",S5t=`uniform vec4 color; `;de.IncludesShadersStore[C5t]=S5t;const E5t="boundingBoxRendererUboDeclaration",T5t=`#ifdef WEBGL2 uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif #else layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; #endif `;de.IncludesShadersStore[E5t]=T5t;const Kqe="boundingBoxRendererPixelShader",Hqe=`#include<__decl__boundingBoxRendererFragment> #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[Kqe]=Hqe;const jqe={name:Kqe,shader:Hqe},AMe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererPixelShader:jqe},Symbol.toStringTag,{value:"Module"})),M5t="boundingBoxRendererVertexDeclaration",R5t=`uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif `;de.IncludesShadersStore[M5t]=R5t;const Xqe="boundingBoxRendererVertexShader",Yqe=`attribute vec3 position; #include<__decl__boundingBoxRendererVertex> #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec4 worldPos=world*vec4(position,1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStore[Xqe]=Yqe;const Qqe={name:Xqe,shader:Yqe},bMe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererVertexShader:Qqe},Symbol.toStringTag,{value:"Module"})),$qe="boundingBoxRendererPixelShader",Zqe=`uniform color: vec4f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN fragmentOutputs.color=uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[$qe]=Zqe;const qqe={name:$qe,shader:Zqe},CMe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererPixelShaderWGSL:qqe},Symbol.toStringTag,{value:"Module"})),Jqe="boundingBoxRendererVertexShader",eJe=`attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f; #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var worldPos: vec4f=uniforms.world* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; #define CUSTOM_VERTEX_MAIN_END } `;de.ShadersStoreWGSL[Jqe]=eJe;const tJe={name:Jqe,shader:eJe},SMe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererVertexShaderWGSL:tJe},Symbol.toStringTag,{value:"Module"})),iJe="linePixelShader",rJe=`#include uniform vec4 color; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #include gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[iJe]=rJe;const sJe={name:iJe,shader:rJe},I5t=Object.freeze(Object.defineProperty({__proto__:null,linePixelShader:sJe},Symbol.toStringTag,{value:"Module"})),P5t="lineVertexDeclaration",w5t=`uniform mat4 viewProjection; #define ADDITIONAL_VERTEX_DECLARATION `;de.IncludesShadersStore[P5t]=w5t;const D5t="lineUboDeclaration",L5t=`layout(std140,column_major) uniform; #include #include `;de.IncludesShadersStore[D5t]=L5t;const nJe="lineVertexShader",aJe=`#include<__decl__lineVertex> #include #include attribute vec3 position;attribute vec4 normal;uniform float width;uniform float aspectRatio; #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN #include mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) vec4 worldPos=finalWorld*vec4(position,1.0); #include #endif #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[nJe]=aJe;const oJe={name:nJe,shader:aJe},O5t=Object.freeze(Object.defineProperty({__proto__:null,lineVertexShader:oJe},Symbol.toStringTag,{value:"Module"})),lJe="linePixelShader",cJe=`#include uniform color: vec4f; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #include fragmentOutputs.color=uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[lJe]=cJe;const uJe={name:lJe,shader:cJe},N5t=Object.freeze(Object.defineProperty({__proto__:null,linePixelShaderWGSL:uJe},Symbol.toStringTag,{value:"Module"})),hJe="lineVertexShader",dJe=`#define ADDITIONAL_VERTEX_DECLARATION #include #include #include #include attribute position: vec3f;attribute normal: vec4f;uniform width: f32;uniform aspectRatio: f32; #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN #include var worldViewProjection: mat4x4f=scene.viewProjection*finalWorld;var viewPosition: vec4f=worldViewProjection* vec4f(input.position,1.0);var viewPositionNext: vec4f=worldViewProjection* vec4f(input.normal.xyz,1.0);var currentScreen: vec2f=viewPosition.xy/viewPosition.w;var nextScreen: vec2f=viewPositionNext.xy/viewPositionNext.w;currentScreen=vec2f(currentScreen.x*uniforms.aspectRatio,currentScreen.y);nextScreen=vec2f(nextScreen.x*uniforms.aspectRatio,nextScreen.y);var dir: vec2f=normalize(nextScreen-currentScreen);var normalDir: vec2f= vec2f(-dir.y,dir.x);normalDir*=uniforms.width/2.0;normalDir=vec2f(normalDir.x/uniforms.aspectRatio,normalDir.y);var offset: vec4f= vec4f(normalDir*input.normal.w,0.0,0.0);vertexOutputs.position=viewPosition+offset; #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) var worldPos: vec4f=finalWorld*vec4f(input.position,1.0); #include #endif #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[hJe]=dJe;const fJe={name:hJe,shader:dJe},F5t=Object.freeze(Object.defineProperty({__proto__:null,lineVertexShaderWGSL:fJe},Symbol.toStringTag,{value:"Module"})),pJe="outlinePixelShader",mJe=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform vec4 color; #ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif #include gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[pJe]=mJe;const gJe={name:pJe,shader:mJe},B5t=Object.freeze(Object.defineProperty({__proto__:null,outlinePixelShader:gJe},Symbol.toStringTag,{value:"Module"})),_Je="outlineVertexShader",vJe=`attribute vec3 position;attribute vec3 normal; #include #include #include #include[0..maxSimultaneousMorphTargets] #include uniform float offset; #include uniform mat4 viewProjection; #ifdef ALPHATEST varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; #ifdef UV1 vec2 uvUpdated=uv; #endif #include #include[0..maxSimultaneousMorphTargets] vec3 offsetPosition=positionUpdated+(normalUpdated*offset); #include #include #include vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; #ifdef ALPHATEST #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include #include } `;de.ShadersStore[_Je]=vJe;const yJe={name:_Je,shader:vJe},k5t=Object.freeze(Object.defineProperty({__proto__:null,outlineVertexShader:yJe},Symbol.toStringTag,{value:"Module"})),xJe="outlinePixelShader",AJe=`uniform color: vec4f; #ifdef ALPHATEST varying vUV: vec2;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include #ifdef ALPHATEST if (textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV).a<0.4) {discard;} #endif #include fragmentOutputs.color=uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[xJe]=AJe;const bJe={name:xJe,shader:AJe},U5t=Object.freeze(Object.defineProperty({__proto__:null,outlinePixelShaderWGSL:bJe},Symbol.toStringTag,{value:"Module"})),CJe="outlineVertexShader",SJe=`attribute position: vec3f;attribute normal: vec3f; #include #include #include #include[0..maxSimultaneousMorphTargets] #include uniform offset: f32; #include uniform viewProjection: mat4x4f; #ifdef ALPHATEST varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input: VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;var normalUpdated: vec3f=vertexInputs.normal; #ifdef UV1 var uvUpdated: vec2f=vertexInputs.uv; #endif #include #include[0..maxSimultaneousMorphTargets] var offsetPosition: vec3f=positionUpdated+(normalUpdated*uniforms.offset); #include #include #include var worldPos: vec4f=finalWorld*vec4f(offsetPosition,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos; #ifdef ALPHATEST #ifdef UV1 vertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef UV2 vertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(vertexInputs.uv2,1.0,0.0)).xy; #endif #endif #include #include } `;de.ShadersStoreWGSL[CJe]=SJe;const EJe={name:CJe,shader:SJe},z5t=Object.freeze(Object.defineProperty({__proto__:null,outlineVertexShaderWGSL:EJe},Symbol.toStringTag,{value:"Module"})),V5t="spriteMapPixelShader",G5t=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=MAX_ANIMATION_FRAMES==0. ? 0. : 1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( texture2D(frameMap,vec2(fX,0.),0.), texture2D(frameMap,vec2(fX,fdStep*1.),0.), texture2D(frameMap,vec2(fX,fdStep*2.),0.), vec4(0.) );} void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); #ifdef FLIPU tileUV.y=1.0-tileUV.y; #endif vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;} animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} color.xyz*=colorMul;gl_FragColor=color;} `;de.ShadersStore[V5t]=G5t;const W5t="spriteMapVertexShader",K5t=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; gl_Position=worldViewProjection*p;}`;de.ShadersStore[W5t]=K5t;class H5t{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,r,n){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=r,r.stageSize=r.stageSize||new we(1,1),r.outputSize=r.outputSize||r.stageSize,r.outputPosition=r.outputPosition||D.Zero(),r.outputRotation=r.outputRotation||D.Zero(),r.layerCount=r.layerCount||1,r.maxAnimationFrames=r.maxAnimationFrames||0,r.baseTile=r.baseTile||0,r.flipU=r.flipU||!1,r.colorMultiply=r.colorMultiply||new D(1,1,1),this._scene=n,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let d=0;d{if(this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture){this._material.setVector2("spriteMapSize",new we(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1));return}c<100&&setTimeout(()=>{c++,u()},100)};u(),this._material.setVector3("colorMul",r.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=b_(e+":output",{size:1,updatable:!0},n),this._output.scaling.x=r.outputSize.x,this._output.scaling.y=r.outputSize.y,this.position=r.outputPosition,this.rotation=r.outputRotation;const h=()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)};this._scene.onBeforeRenderObservable.add(h),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||we.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,r=>r===e);if(!t||!t.hit||!t.getTextureCoordinates)return new we(-1,-1);const i=t.getTextureCoordinates();return i||new we(-1,-1)}_createFrameBuffer(){const e=[];for(let r=0;r0&&(e+=` \r`),e+=this._tileMaps[i]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const r=t.response.split(` \r`);for(let n=0;n{e.dispose()}),this._frameMap.dispose()}}class j5t extends Xm{constructor(e,t,i,r,n=null,a=.01,o=xe.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,r,a,o,!0,n),this.name=e}}const X5t="imageProcessingCompatibility",Y5t=`#ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); #endif `;de.IncludesShadersStore[X5t]=Y5t;const TJe="spritesPixelShader",MJe=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; #include #include #define CUSTOM_FRAGMENT_DEFINITIONS #ifdef PIXEL_PERFECT vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} #endif void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #ifdef PIXEL_PERFECT vec2 uv=uvPixelPerfect(vUV); #else vec2 uv=vUV; #endif vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) {if (color.a<0.95) discard;} color*=vColor; #include #include gl_FragColor=color; #include #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[TJe]=MJe;const RJe={name:TJe,shader:MJe},Q5t=Object.freeze(Object.defineProperty({__proto__:null,spritesPixelShader:RJe},Symbol.toStringTag,{value:"Module"})),IJe="spritesVertexShader",PJe=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; #include #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; #ifdef FOG vFogDistance=viewPos; #endif #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[IJe]=PJe;const wJe={name:IJe,shader:PJe},$5t=Object.freeze(Object.defineProperty({__proto__:null,spritesVertexShader:wJe},Symbol.toStringTag,{value:"Module"})),Z5t="imageProcessingCompatibility",q5t=`#ifdef IMAGEPROCESSINGPOSTPROCESS fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a); #endif `;de.IncludesShadersStoreWGSL[Z5t]=q5t;const DJe="spritesPixelShader",LJe=`uniform alphaTest: i32;varying vColor: vec4f;varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #include #include #define CUSTOM_FRAGMENT_DEFINITIONS #ifdef PIXEL_PERFECT fn uvPixelPerfect(uv: vec2f)->vec2f {var res: vec2f= vec2f(textureDimensions(diffuseSampler,0));var uvTemp=uv*res;var seam: vec2f=floor(uvTemp+0.5);uvTemp=seam+clamp((uvTemp-seam)/fwidth(uvTemp),vec2f(-0.5),vec2f(0.5));return uvTemp/res;} #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #ifdef PIXEL_PERFECT var uv: vec2f=uvPixelPerfect(input.vUV); #else var uv: vec2f=input.vUV; #endif var color: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,uv);var fAlphaTest: f32= f32(uniforms.alphaTest);if (fAlphaTest != 0.) {if (color.a<0.95) {discard;}} color*=input.vColor; #include #include fragmentOutputs.color=color; #include #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStoreWGSL[DJe]=LJe;const OJe={name:DJe,shader:LJe},J5t=Object.freeze(Object.defineProperty({__proto__:null,spritesPixelShaderWGSL:OJe},Symbol.toStringTag,{value:"Module"})),NJe="spritesVertexShader",FJe=`attribute position: vec4f;attribute options: vec2f;attribute offsets: vec2f;attribute inverts: vec2f;attribute cellInfo: vec4f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;varying vUV: vec2f;varying vColor: vec4f; #include #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var viewPos: vec3f=(uniforms.view* vec4f(input.position.xyz,1.0)).xyz; var cornerPos: vec2f;var angle: f32=input.position.w;var size: vec2f= vec2f(input.options.x,input.options.y);var offset: vec2f=input.offsets.xy;cornerPos= vec2f(offset.x-0.5,offset.y -0.5)*size;var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0); vertexOutputs.vColor=input.color;var uvOffset: vec2f= vec2f(abs(offset.x-input.inverts.x),abs(1.0-offset.y-input.inverts.y));var uvPlace: vec2f=input.cellInfo.xy;var uvSize: vec2f=input.cellInfo.zw;vertexOutputs.vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vertexOutputs.vUV.y=uvPlace.y+uvSize.y*uvOffset.y; #ifdef FOG vertexOutputs.vFogDistance=viewPos; #endif #include #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStoreWGSL[NJe]=FJe;const BJe={name:NJe,shader:FJe},ePt=Object.freeze(Object.defineProperty({__proto__:null,spritesVertexShaderWGSL:BJe},Symbol.toStringTag,{value:"Module"}));var Wde;(function(s){s[s.INIT=0]="INIT",s[s.RUNNING=1]="RUNNING",s[s.DONE=2]="DONE",s[s.ERROR=3]="ERROR"})(Wde||(Wde={}));class xg{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=0}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=1,this.runTask(e,()=>{this._onDoneCallback(t,i)},(r,n)=>{this._onErrorCallback(i,r,n)})}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=0}_onErrorCallback(e,t,i){this._taskState=3,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=2,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(i){this._onErrorCallback(t,"Task is done, error executing success callback(s)",i)}}}class kJe{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class UJe extends xg{constructor(e,t,i,r,n){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=n}runTask(e,t,i){Ys.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,r=>{this.loadedContainer=r,this.loadedMeshes=r.meshes,this.loadedTransformNodes=r.transformNodes,this.loadedParticleSystems=r.particleSystems,this.loadedSkeletons=r.skeletons,this.loadedAnimationGroups=r.animationGroups,t()},null,(r,n,a)=>{i(n,a)},this.extension)}}class zJe extends xg{constructor(e,t,i,r,n){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=n}runTask(e,t,i){Ys.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,(r,n,a,o,l)=>{this.loadedMeshes=r,this.loadedTransformNodes=l,this.loadedParticleSystems=n,this.loadedSkeletons=a,this.loadedAnimationGroups=o,t()},null,(r,n,a)=>{i(n,a)},this.extension)}}class tPt extends xg{constructor(e,t,i,r,n){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=r,this.extension=n}runTask(e,t,i){const r=e.animatables.length,n=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],Ys.ImportAnimations(this.rootUrl,this.filename,e,!1,3,this.targetConverter,()=>{this.loadedAnimatables=e.animatables.slice(r),this.loadedAnimationGroups=e.animationGroups.slice(n),t()},null,(a,o,l)=>{i(o,l)},this.extension)}}class VJe extends xg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,r=>{this.text=r,t()},void 0,!1,!1,(r,n)=>{r&&i(r.status+" "+r.statusText,n)})}}class GJe extends xg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,r=>{this.data=r,t()},void 0,!0,!0,(r,n)=>{r&&i(r.status+" "+r.statusText,n)})}}class WJe extends xg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const r=new Image;Me.SetCorsBehavior(this.url,r),r.onload=()=>{this.image=r,t()},r.onerror=n=>{i("Error loading image",n)},r.src=this.url}}class KJe extends xg{constructor(e,t,i,r=!0,n=xe.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=r,this.samplingMode=n}runTask(e,t,i){const r=()=>{t()},n=(a,o)=>{i(a,o)};this.texture=new xe(this.url,e,this.noMipmap,this.invertY,this.samplingMode,r,n)}}class HJe extends xg{constructor(e,t,i,r,n,a){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=r,this.files=n,this.prefiltered=a}runTask(e,t,i){const r=()=>{t()},n=(a,o)=>{i(a,o)};this.texture=new _a(this.url,e,this.extensions,this.noMipmap,this.files,r,n,void 0,this.prefiltered)}}class jJe extends xg{constructor(e,t,i,r=!1,n=!0,a=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.generateHarmonics=n,this.gammaSpace=a,this.reserved=o}runTask(e,t,i){const r=()=>{t()},n=(a,o)=>{i(a,o)};this.texture=new e_(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,r,n)}}class XJe extends xg{constructor(e,t,i,r=!1,n=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.gammaSpace=n}runTask(e,t,i){const r=()=>{t()},n=(a,o)=>{i(a,o)};this.texture=new ow(this.url,e,this.size,this.noMipmap,this.gammaSpace,r,n)}}class iPt{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new Ae,this.onTaskErrorObservable=new Ae,this.onTasksDoneObservable=new Ae,this.onProgressObservable=new Ae,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||Rt.LastCreatedScene}addContainerTask(e,t,i,r,n){const a=new UJe(e,t,i,r,n);return this._tasks.push(a),a}addMeshTask(e,t,i,r,n){const a=new zJe(e,t,i,r,n);return this._tasks.push(a),a}addTextFileTask(e,t){const i=new VJe(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new GJe(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new WJe(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,r,n=xe.TRILINEAR_SAMPLINGMODE){const a=new KJe(e,t,i,r,n);return this._tasks.push(a),a}addCubeTextureTask(e,t,i,r,n,a){const o=new HJe(e,t,i,r,n,a);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,r=!1,n=!0,a=!1,o=!1){const l=new jJe(e,t,i,r,n,a,o);return this._tasks.push(l),l}addEquiRectangularCubeTextureAssetTask(e,t,i,r=!1,n=!0){const a=new XJe(e,t,i,r,n);return this._tasks.push(a),a}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new kJe(this._waitingTasksCount,this._totalTasksCount,e))}catch(t){fe.Error("Error running progress callbacks."),fe.Log(t)}if(this._waitingTasksCount===0){try{const t=this._tasks.slice();this.onFinish&&this.onFinish(t);for(const i of t)if(i.taskState===2){const r=this._tasks.indexOf(i);r>-1&&this._tasks.splice(r,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){fe.Error("Error running tasks-done callbacks."),fe.Log(t)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(r){i("Error executing task success callbacks",r)}},i=(r,n)=>{e._setErrorObject(r,n),this.onTaskError?this.onTaskError(e):e.onError||fe.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,t,i)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,this._waitingTasksCount===0)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{if(this._isLoading){e();return}this.onTasksDoneObservable.addOnce(i=>{i&&i.length?t(i):e()}),this.load()})}}class uS{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class rPt{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new D(1,1,1),this._newPosition=D.Zero(),this._centerPosition=D.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let r=0;r!0,this.displayLoadingUI=!0,this.loadAsync=(h,d)=>this.useAppend?Ys.AppendAsync("file:",h,this._currentScene,d):Ys.LoadAsync("file:",h,this._engine,d),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=r,this._additionalRenderLoopLogicCallback=n,this._textureLoadingCallback=a,this._startingProcessingFilesCallback=o,this._onReloadCallback=l,this._errorCallback=c}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=t=>{this._drag(t)},this._dragOverHandler=t=>{this._drag(t)},this._dropHandler=t=>{this._drop(t)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,r){const n=e.createReader(),a=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");n.readEntries(o=>{i.count+=o.length;for(const l of o)l.isFile?l.file(c=>{c.correctName=a+c.name,t.push(c),--i.count===0&&r()}):l.isDirectory&&this._traverseFolder(l,t,i,r);--i.count===0&&r()})}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=n)&&(Ys.IsPluginForExtensionAvailable("."+r)&&(this._sceneFileToLoad=e[t]),H_e.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),!(!this._filesToLoad||this._filesToLoad.length===0)&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],r=e.dataTransfer?e.dataTransfer.items:null;for(let n=0;n{this._processFiles(t),n.count===0&&this._processReload()})}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){if(this._sceneFileToLoad)this.useAppend||this._currentScene&&(fe.errorsCount>0&&fe.ClearLogCache(),this._engine.stopRenderLoop()),Ys.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then(e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady(()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop(()=>{this._renderFunction()})})),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)}).catch(e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)});else{if(this._filesToLoad.length===1){const t=this._filesToLoad[0].name.toLowerCase().split(".").pop();if(t)switch(t.toLowerCase()){case"dds":case"env":case"hdr":return}}fe.Error("Please provide a valid .babylon file.")}}}class j_e{dispose(){if(this._observers&&this._observables)for(let e=0;e{a.skipNextObservers||o._willBeUnregistered||o.mask&e&&(o.scope?n=n.then(l=>(a.lastReturnValue=l,o.callback.apply(o.scope,[s,a]))):n=n.then(l=>(a.lastReturnValue=l,o.callback(s,a))),o.unregisterOnNextCall&&this._deferUnregister(o))}),await n,s};class S_{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class qQ extends S_{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let r=0;rthis.maximumSize&&(n.scale(this.step),i=!1)}return i}}class Kde extends S_{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return this._currentScale===-1&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),this._directionOffset===1?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class JQ extends S_{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class e$ extends S_{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class t$ extends S_{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class YJe extends S_{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return this.onApply?this.onApply(e,t):!0}}class i$ extends S_{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class Hde extends S_{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class Mv extends S_{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Ee))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||t.getTotalVertices()===0)}}static get UpdateSelectionTree(){return Mv._UpdateSelectionTree}static set UpdateSelectionTree(e){Mv._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const r=e.meshes.slice(0);let n=r.length;for(let o=0;o{this._sceneDisposeObserver=null,this.dispose()})}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady(()=>{setTimeout(()=>{this._checkCurrentState()},this._trackerDuration)}))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate){this._isRunning=!1,this.onSuccessObservable.notifyObservers(this);return}let i=!0,r=!0;for(let n=0;n{setTimeout(()=>{this._checkCurrentState()},this._trackerDuration)})}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,r){const n=new X_e(e,t||LS.ModerateDegradationAllowed(),!1);return i&&n.onSuccessObservable.add(()=>{i()}),r&&n.onFailureObservable.add(()=>{r()}),n.start(),n}}let jde=[];const Y_e=(s,e)=>{s.doNotSerialize||(e.vertexData.push(s.serializeVerticeData()),jde[s.id]=!0)},QJe=(s,e)=>{const t={},i=s._geometry;return i&&(s.getScene().getGeometryById(i.id)||Y_e(i,e.geometries)),s.serialize&&s.serialize(t),t},sPt=(s,e)=>{if(s._isMesh){const t=s;if(t.delayLoadState===1||t.delayLoadState===0){const i=n=>{e.materials=e.materials||[],t.material&&!e.materials.some(a=>a.id===t.material.id)&&e.materials.push(n.serialize())};if(t.material&&!t.material.doNotSerialize)if(t.material instanceof Zd){if(e.multiMaterials=e.multiMaterials||[],!e.multiMaterials.some(n=>n.id===t.material.id)){e.multiMaterials.push(t.material.serialize());for(const n of t.material.subMaterials)n&&i(n)}}else i(t.material);else t.material||i(t.getScene().defaultMaterial);const r=t._geometry;r&&(e.geometries||(e.geometries={},e.geometries.boxes=[],e.geometries.spheres=[],e.geometries.cylinders=[],e.geometries.toruses=[],e.geometries.grounds=[],e.geometries.planes=[],e.geometries.torusKnots=[],e.geometries.vertexData=[]),Y_e(r,e.geometries)),t.skeleton&&!t.skeleton.doNotSerialize&&(e.skeletons=e.skeletons||[],e.skeletons.push(t.skeleton.serialize())),e.meshes=e.meshes||[],e.meshes.push(QJe(t,e))}}else if(s.getClassName()==="TransformNode"){const t=s;e.transformNodes.push(t.serialize())}else if(s.getClassName().indexOf("Camera")!==-1){const t=s;e.cameras.push(t.serialize())}else if(s.getClassName().indexOf("Light")!==-1){const t=s;e.lights.push(t.serialize())}};class X1{static ClearCache(){jde=[]}static Serialize(e){return X1._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&xe.ForceSerializeBuffers&&fe.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),X1.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode!==void 0&&e.fogMode!==null&&(i.fogMode=e.fogMode),e.fogColor!==void 0&&e.fogColor!==null&&(i.fogColor=e.fogColor.asArray()),e.fogStart!==void 0&&e.fogStart!==null&&(i.fogStart=e.fogStart),e.fogEnd!==void 0&&e.fogEnd!==null&&(i.fogEnd=e.fogEnd),e.fogDensity!==void 0&&e.fogDensity!==null&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const l=e.getPhysicsEngine();l&&(i.physicsEnabled=!0,i.physicsGravity=l.gravity.asArray(),i.physicsEngine=l.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const l of e.meshes){const c=l.morphTargetManager;c&&i.morphTargetManagers.push(c.serialize())}i.lights=[];let r,n;for(r=0;r0){i.animationGroups=[];for(let l=0;l0)for(i.reflectionProbes=[],r=0;rt)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=n)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const r=e[i];r instanceof Promise?t.push(r.then(n=>e[i]=n)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){const r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],X1.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let n=0;n{e.indexOf(a)<0&&!a.doNotSerialize&&e.push(a)}),t&&e[n].parent&&e.indexOf(e[n].parent)<0&&!e[n].parent.doNotSerialize&&e.push(e[n].parent);return e.forEach(n=>{sPt(n,r)}),r}}class Zk{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&typeof i.captureStream=="function"}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!Zk.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...Zk._DefaultOptions,...t};const r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const n of this._options.audioTracks)r.addTrack(n);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=n=>this._handleDataAvailable(n),this._mediaRecorder.onerror=n=>this._handleError(n),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){!this._canvas||!this._mediaRecorder||this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(()=>{this.stopRecording()},t*1e3),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((i,r)=>{this._resolve=i,this._reject=r})}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),this._reject)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Me.Download(e,this._fileName)}}Zk._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let ry=null;function cV(s,e,t,i,r="image/png",n=!1,a){const{height:o,width:l}=ZJe(s,e,t);if(!(o&&l)){fe.Error("Invalid 'size' parameter !");return}ry||(ry=document.createElement("canvas")),ry.width=l,ry.height=o;const c=ry.getContext("2d"),u=s.getRenderWidth()/s.getRenderHeight();let h=l,d=h/u;d>o&&(d=o,h=d*u);const f=Math.max(0,l-h)/2,p=Math.max(0,o-d)/2;e.getScene().activeCamera!==e?uV(s,e,t,g=>{if(n){const _=new Blob([g]);Me.DownloadBlob(_),i&&i("")}else i&&i(g)},r,1,s.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):s.onEndFrameObservable.addOnce(()=>{const g=s.getRenderingCanvas();c&&g&&c.drawImage(g,f,p,h,d),ry&&(n?(Me.EncodeScreenshotCanvasData(ry,void 0,r,void 0,a),i&&i("")):Me.EncodeScreenshotCanvasData(ry,i,r,void 0,a))})}function Q_e(s,e,t,i="image/png",r){return new Promise((n,a)=>{cV(s,e,t,o=>{typeof o<"u"?n(o):a(new Error("Data is undefined"))},i,void 0,r)})}function $Je(s,e,t,i,r="image/png",n){return new Promise(a=>{cV(s,e,{width:t,height:i},()=>{a()},r,!0,n)})}function uV(s,e,t,i,r="image/png",n=1,a=!1,o,l=!1,c=!1,u=!0,h,d){const{height:f,width:p,finalWidth:m,finalHeight:g}=ZJe(s,e,t),_={width:p,height:f};if(!(f&&p)){fe.Error("Invalid 'size' parameter !");return}const y={width:s.getRenderWidth(),height:s.getRenderHeight()};s.setSize(p,f);const v=e.getScene(),x=new Rs("screenShot",_,v,!1,!1,0,!1,xe.BILINEAR_SAMPLINGMODE,void 0,c,void 0,void 0,void 0,n);x.renderList=v.meshes.slice(),x.samples=n,x.renderSprites=l,x.activeCamera=e,x.forceLayerMaskCheck=u,d==null||d(x);const A=()=>{x.isReadyForRendering()&&e.isReady(!0)?(s.onEndFrameObservable.addOnce(()=>{m===p&&g===f?x.readPixels(void 0,void 0,void 0,!1).then(C=>{e6(p,f,C,i,r,o,!0,void 0,h),x.dispose()}):aee("pass",x.getInternalTexture(),v,void 0,void 0,void 0,m,g).then(C=>{s._readTexturePixels(C,m,g,-1,0,null,!0,!1,0,0).then(T=>{e6(m,g,T,i,r,o,!0,void 0,h),C.dispose()})})}),v.incrementRenderId(),v.resetCachedMaterial(),x.render(!0),s.setSize(y.width,y.height),e.getProjectionMatrix(!0),v.render()):setTimeout(A,16)},b=()=>{v.incrementRenderId(),v.resetCachedMaterial(),A()};if(a){const C=new pT("antialiasing",1,v.activeCamera);x.addPostProcess(C),C.onEffectCreatedObservable.addOnce(T=>{T.isReady()?b():T.onCompiled=()=>{b()}})}else b()}function $_e(s,e,t,i="image/png",r=1,n=!1,a,o=!1,l=!1,c=!0,u){return new Promise((h,d)=>{uV(s,e,t,f=>{typeof f<"u"?h(f):d(new Error("Data is undefined"))},i,r,n,a,o,l,c,u)})}function ZJe(s,e,t){let i=0,r=0,n=0,a=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,r=t.width*o):t.width&&!t.height?(r=t.width*o,i=Math.round(r/s.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,r=Math.round(i*s.getAspectRatio(e))):(r=Math.round(s.getRenderWidth()*o),i=Math.round(r/s.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(a=t.finalHeight,n=t.finalWidth):t.finalWidth&&!t.finalHeight?(n=t.finalWidth,a=Math.round(n/s.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(a=t.finalHeight,n=Math.round(a*s.getAspectRatio(e))):(n=r,a=i)}else isNaN(t)||(i=t,r=t,n=t,a=t);return r&&(r=Math.floor(r)),i&&(i=Math.floor(i)),n&&(n=Math.floor(n)),a&&(a=Math.floor(a)),{height:i|0,width:r|0,finalWidth:n|0,finalHeight:a|0}}const nPt={CreateScreenshot:cV,CreateScreenshotAsync:Q_e,CreateScreenshotWithResizeAsync:$Je,CreateScreenshotUsingRenderTarget:uV,CreateScreenshotUsingRenderTargetAsync:$_e},aPt=()=>{Me.CreateScreenshot=cV,Me.CreateScreenshotAsync=Q_e,Me.CreateScreenshotUsingRenderTarget=uV,Me.CreateScreenshotUsingRenderTargetAsync=$_e};aPt();var Xde;(function(s){s[s.Checkbox=0]="Checkbox",s[s.Slider=1]="Slider",s[s.Vector3=2]="Vector3",s[s.Quaternion=3]="Quaternion",s[s.Color3=4]="Color3",s[s.String=5]="String",s[s.Button=6]="Button",s[s.Options=7]="Options",s[s.Tab=8]="Tab",s[s.FileButton=9]="FileButton",s[s.Vector2=10]="Vector2"})(Xde||(Xde={}));class yB{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then(t=>{this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._dataByteOffset=0})}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return age(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class Yde{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return i===void 0?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return i!==null?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return i!==null?i==="true":t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return i!==null?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}Yde._Storage=Yde._GetStorage();class oPt{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,qe.AllowLoadingUniqueId=!0,this._savedJSON=X1.Serialize(e),qe.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=xe.ForceSerializeBuffers;xe.ForceSerializeBuffers=!1,qe.AllowLoadingUniqueId=!0;const t=X1.Serialize(this._trackedScene);qe.AllowLoadingUniqueId=!1;const i={};for(const r in t)this._compareCollections(r,this._savedJSON[r],t[r],i);return xe.ForceSerializeBuffers=e,i}_compareArray(e,t,i,r){if(t.length===0&&i.length===0)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(t.length===0)return!0;for(let a=0;au.uniqueId===l);if(c.length){const u=c[0],h={};this._compareObjects(o,u,h)||(r[e]||(r[e]=[]),h.__state={id:u.id||u.name},r[e].push(h))}else{const u={__state:{deleteId:o.id||o.name}};r[e]||(r[e]=[]),r[e].push(u)}}for(let a=0;ar.getShadowGenerators());for(const r of i)if(r){const n=r.values();for(let a=n.next();a.done!==!0;a=n.next()){const o=a.value;if(o&&o.id===t)return o}}return null}static ApplyDelta(e,t){typeof e=="string"&&(e=JSON.parse(e));const i=t;for(const r in e){const n=e[r],a=i[r];if(Array.isArray(a)||r==="shadowGenerators")switch(r){case"cameras":this._ApplyDeltaForEntity(n,t,t.getCameraById.bind(t),o=>Nt.Parse(o,t));break;case"lights":this._ApplyDeltaForEntity(n,t,t.getLightById.bind(t),o=>Zi.Parse(o,t));break;case"shadowGenerators":this._ApplyDeltaForEntity(n,t,o=>this.GetShadowGeneratorById(t,o),o=>pi.Parse(o,t));break;case"meshes":this._ApplyDeltaForEntity(n,t,t.getMeshById.bind(t),o=>Ee.Parse(o,t,""));break;case"skeletons":this._ApplyDeltaForEntity(n,t,t.getSkeletonById.bind(t),o=>cg.Parse(o,t));break;case"materials":this._ApplyDeltaForEntity(n,t,t.getMaterialById.bind(t),o=>Ye.Parse(o,t,""));break;case"multiMaterials":this._ApplyDeltaForEntity(n,t,t.getMaterialById.bind(t),o=>Zd.Parse(o,t,""));break;case"transformNodes":this._ApplyDeltaForEntity(n,t,t.getTransformNodeById.bind(t),o=>_t.Parse(o,t,""));break;case"particleSystems":this._ApplyDeltaForEntity(n,t,t.getParticleSystemById.bind(t),o=>bs.Parse(o,t,""));break;case"morphTargetManagers":this._ApplyDeltaForEntity(n,t,t.getMorphTargetById.bind(t),o=>f0.Parse(o,t));break;case"postProcesses":this._ApplyDeltaForEntity(n,t,t.getPostProcessByName.bind(t),o=>Ft.Parse(o,t,""));break}else isNaN(a)?a.fromArray&&a.fromArray(n):i[r]=n}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const r=e[i],n=t[i];n!==void 0&&(!isNaN(n)||Array.isArray(n)?t[i]=r:n.fromArray?n.fromArray(r):typeof n=="object"&&n!==null&&this._ApplyPropertiesToEntity(r,n))}}static _ApplyDeltaForEntity(e,t,i,r){for(const n of e)if(n.__state&&n.__state.id!==void 0){const a=i(n.__state.id);a&&(this._ApplyPropertiesToEntity(n,a),qe.ParseProperties(n,a,t,null))}else if(n.__state&&n.__state.deleteId!==void 0){const a=i(n.__state.deleteId);a==null||a.dispose()}else r(n)}}var mw;(function(s){class e{serialize(){const r={},n=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((a,o)=>{n[a]=o}),r.characters=n,r.insertionCosts=this._insertionCosts,r.deletionCosts=this._deletionCosts,r.substitutionCosts=this._substitutionCosts,JSON.stringify(r)}static Deserialize(r){const n=JSON.parse(r),a=new e(n.characters);return a._insertionCosts=n.insertionCosts,a._deletionCosts=n.deletionCosts,a._substitutionCosts=n.substitutionCosts,a}constructor(r,n=null,a=null,o=null){n=n??(()=>1),a=a??(()=>1),o=o??((c,u)=>c===u?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(r.length),this._deletionCosts=new Array(r.length),this._substitutionCosts=new Array(r.length);let l;for(let c=0;ct._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+t._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=n,this._characters=r.map(a=>this._alphabet.getCharacterIdx(a))}distance(r){return t._Distance(this,r)}static _Distance(r,n){const a=r._alphabet;if(a!==n._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const o=r._characters,l=n._characters,c=o.length,u=l.length,h=t._CostMatrix;h[0][0]=0;for(let d=0;dnew Array(t._MAX_SEQUENCE_LENGTH+1)),s.Sequence=t})(mw||(mw={}));class Ws{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new Ws(t._segmentLength);return i._points=t._points.map(r=>new D(r._x,r._y,r._z)),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(t===0)this._points.push(e.clone());else{const i=()=>this._segmentLength/D.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){const n=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,n),this._points.push(n),++t}}}resampleAtTargetResolution(e){const t=new Ws(this.getLength()/e);return this._points.forEach(i=>{t.add(i)}),t}tokenize(e){const t=[],i=new D;for(let r=2;r.98?!1:(D.CrossToRef(Ws._ForwardDir,Ws._InverseFromVec,Ws._UpDir),Ws._UpDir.normalize(),he.LookAtLHToRef(e,t,Ws._UpDir,Ws._LookMatrix),i.subtractToRef(t,Ws._FromToVec),Ws._FromToVec.normalize(),D.TransformNormalToRef(Ws._FromToVec,Ws._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Ws._BestMatch=0,Ws._Score=D.Dot(e,t[0]),Ws._BestScore=Ws._Score;for(let i=1;iWs._BestScore&&(Ws._BestMatch=i,Ws._BestScore=Ws._Score);return Ws._BestMatch}}Ws._ForwardDir=new D;Ws._InverseFromVec=new D;Ws._UpDir=new D;Ws._FromToVec=new D;Ws._LookMatrix=new he;class qk{static Generate(e=64,t=256,i=.1,r=.001,n=[]){const l=new qk(e);for(let p=0;p(1-g)*p+g*m;for(let p=0;p{l.chars[m].subtractToRef(g,d),u=d.lengthSquared(),u>1e-6&&d.scaleAndAddToRef(1/(d.lengthSquared()*u),h)}),h.scaleInPlace(c),l.chars[m].addInPlace(h),l.chars[m].normalize()}return l}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new qk(t.length);for(let r=0;re.serialize()))}static Deserialize(e,t){const i=new F1;return i._sequences=JSON.parse(e).map(r=>mw.Sequence.Deserialize(r,t)),i}static CreateFromTrajectory(e,t,i){return F1.CreateFromTokenizationPyramid(F1._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new F1;return i._sequences=e.map(r=>new mw.Sequence(r,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=F1._FINEST_DESCRIPTOR_RESOLUTION){const r=[];for(let n=i;n>4;n=Math.floor(n/2))r.push(e.resampleAtTargetResolution(n).tokenize(t.chars));return r}distance(e){let t=0,i;for(let r=0;rt.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),r=new gw;return r._descriptors=i.descriptors.map(n=>F1.Deserialize(n,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){this._centroidIdx=-1;let e;const t=this._descriptors.map(i=>(e=0,this._descriptors.forEach(r=>{e+=i.distance(r)}),e));for(let i=0;i{this._averageDistance+=i.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,gw._MIN_AVERAGE_DISTANCE))}}gw._MIN_AVERAGE_DISTANCE=1;class MZ{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())}),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new MZ;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=qk.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=mw.Alphabet.Deserialize(t.levenshteinAlphabet);for(let r=0;rn===0?0:1,n=>n===0?0:1,(n,a)=>Math.min(1-D.Dot(e.chars[n],e.chars[a]),1)),r=new MZ;return r._vector3Alphabet=e,r._levenshteinAlphabet=i,r}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new gw),this._nameToDescribedTrajectory.get(t).add(F1.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=F1.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach((o,l)=>{o.getMatchCost(t){const n=r.data;if(n.startsWith(Jk._SERVER_PREFIX)){const a=n.substr(Jk._SERVER_PREFIX.length);fe.Log(`[Reflector] Received server message: ${a.substr(0,64)}`),this._handleServerMessage(a);return}else fe.Log(`[Reflector] Received client message: ${n.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=r=>{fe.Log(`[Reflector] Disconnected ${r.code} ${r.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){switch(e){case"connected":{X1.SerializeAsync(this._scene).then(t=>{this._webSocket.send(`load|${JSON.stringify(t)}`)});break}}}_handleClientMessage(){}}Jk._SERVER_PREFIX="$$";class Xee{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new Ae,Xee.IsAvailable&&(this._observer=new PressureObserver(t=>{this._currentState=t,this.onPressureChanged.notifyObservers(t)},e))}static get IsAvailable(){return typeof PressureObserver<"u"&&PressureObserver.knownSources&&PressureObserver.knownSources.includes("cpu")}observe(e){var t;try{(t=this._observer)==null||t.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){var t;try{(t=this._observer)==null||t.unobserve(e)}catch{}}dispose(){var e;(e=this._observer)==null||e.disconnect(),this._observer=null,this.onPressureChanged.clear()}}const lPt=1.5;class j2{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(this._view.length*lPt),t=new Float32Array(e);t.set(this._view),this._view=t}}const sy=1800,cPt=24,uPt="0",EMe="timestamp",TMe="numPoints",hPt=/\r/g,Yne="@";class jp{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=Or.Now-this._startingTimestamp,r=this.datasets.ids.length,n=this.datasets.startingIndices.itemLength;let a=0;if(n>0){const o=this.datasets.startingIndices.at(n-1);a=o+this.datasets.data.at(o+jp.NumberOfPointsOffset)+jp.SliceDataOffset}if(this.datasets.startingIndices.push(a),this.datasets.data.push(i),this.datasets.data.push(r),this.datasets.ids.forEach(o=>{const l=this._strategies.get(o);l&&this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const o=[i,r];for(let l=0;li.callback(this._datasetMeta,new $me(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var a;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((a=this._strategies.get(e))==null||a.dispose(),this._strategies.delete(e));const r=o=>{let l=0,c=0;const u=o.onAfterRenderObservable.add(()=>{c=l,l=0}),h=this._customEventObservable.add(d=>{e===d.name&&(d.value!==void 0?l=d.value:l++)});return{id:e,getData:()=>c,dispose:()=>{o.onAfterRenderObservable.remove(u),this._customEventObservable.remove(h)}}},n={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:r,category:i}),n}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){const n=t(this._scene);if(this._strategies.has(n.id)){n.dispose();continue}this.datasets.ids.push(n.id),i&&(i=i.replace(new RegExp(Yne,"g"),"")),this._datasetMeta.set(n.id,{color:this._getHexColorFromId(n.id),category:i,hidden:r}),this._strategies.set(n.id,n)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let r=0;r>r&255;i+=(uPt+n.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=Or.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(r=>{const n=this._strategies.get(r);n&&this.datasetObservable.hasObservers()&&i.push(n.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){const r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new j2(sy),this.datasets.ids.length=0,this.datasets.startingIndices=new j2(sy),this._datasetMeta.clear(),this._strategies.forEach(t=>t.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(hPt,"").split(` `).map(h=>h.split(",").filter(d=>d.length>0)).filter(h=>h.length>0),r=0,n=jp.NumberOfPointsOffset;if(i.length<2)return!1;const a={ids:[],data:new j2(sy),startingIndices:new j2(sy)},[o,...l]=i;if(o.length<2||o[r]!==EMe||o[n]!==TMe)return!1;const c=new Map;for(let h=jp.SliceDataOffset;hh.dispose()),this._strategies.clear(),!t)for(const h of this.datasets.ids){const d=c.get(h);this._datasetMeta.set(h,{category:d,color:this._getHexColorFromId(h)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${EMe},${TMe}`;for(let i=0;i{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const kp=()=>{};class dPt{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:kp}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const r=new Xee;return r.observe("cpu"),r.onPressureChanged.add(n=>{var a;for(const o of n)if(t&&o.factors.includes(t)||!t&&(((a=o.factors)==null?void 0:a.length)??0)===0)switch(o.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1;break}}),{id:e,getData:()=>i,dispose:()=>r.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:kp})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:kp})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:kp})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:kp})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:kp})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:kp})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add(()=>{e.getEngine()._drawCalls.fetchNewFrame()}),r=e.onAfterRenderObservable.add(()=>{t=e.getEngine()._drawCalls.current});return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(r)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:kp})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:kp})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:kp})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:kp})}static AbsoluteFpsStrategy(){return e=>{const t=new AUe(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:kp}}}static MeshesSelectionStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeActiveMeshesEvaluationObservable.add(()=>{t=Or.Now}),n=e.onAfterActiveMeshesEvaluationObservable.add(()=>{i=Or.Now-t});return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(r),e.onAfterActiveMeshesEvaluationObservable.remove(n)}}}}static RenderTargetsStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeRenderTargetsRenderObservable.add(()=>{t=Or.Now}),n=e.onAfterRenderTargetsRenderObservable.add(()=>{i=Or.Now-t});return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(r),e.onAfterRenderTargetsRenderObservable.remove(n)}}}}static ParticlesStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeParticlesRenderingObservable.add(()=>{t=Or.Now}),n=e.onAfterParticlesRenderingObservable.add(()=>{i=Or.Now-t});return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(r),e.onAfterParticlesRenderingObservable.remove(n)}}}}static SpritesStrategy(){return e=>{var a,o;let t=Or.Now,i=0;const r=(a=e.onBeforeSpritesRenderingObservable)==null?void 0:a.add(()=>{t=Or.Now}),n=(o=e.onAfterSpritesRenderingObservable)==null?void 0:o.add(()=>{i=Or.Now-t});return{id:"Sprites",getData:()=>i,dispose:()=>{var l,c;(l=e.onBeforeSpritesRenderingObservable)==null||l.remove(r),(c=e.onAfterSpritesRenderingObservable)==null||c.remove(n)}}}}static AnimationsStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeAnimationsObservable.add(()=>{t=Or.Now}),n=e.onAfterAnimationsObservable.add(()=>{i=Or.Now-t});return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterAnimationsObservable.remove(n)}}}}static PhysicsStrategy(){return e=>{var a,o;let t=Or.Now,i=0;const r=(a=e.onBeforePhysicsObservable)==null?void 0:a.add(()=>{t=Or.Now}),n=(o=e.onAfterPhysicsObservable)==null?void 0:o.add(()=>{i=Or.Now-t});return{id:"Physics",getData:()=>i,dispose:()=>{var l,c;(l=e.onBeforePhysicsObservable)==null||l.remove(r),(c=e.onAfterPhysicsObservable)==null||c.remove(n)}}}}static RenderStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeDrawPhaseObservable.add(()=>{t=Or.Now}),n=e.onAfterDrawPhaseObservable.add(()=>{i=Or.Now-t});return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(r),e.onAfterDrawPhaseObservable.remove(n)}}}}static FrameTotalStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeAnimationsObservable.add(()=>{t=Or.Now}),n=e.onAfterRenderObservable.add(()=>{i=Or.Now-t});return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(n)}}}}static InterFrameStrategy(){return e=>{let t=Or.Now,i=0;const r=e.onBeforeAnimationsObservable.add(()=>{i=Or.Now-t}),n=e.onAfterRenderObservable.add(()=>{t=Or.Now});return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(n)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new xUe(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(t.gpuFrameTimeCounter.current*1e-6,0),dispose:()=>{t.dispose()}}}}}gt.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new jp(this)),this._perfCollector};function fPt(s){const e=new Array,t=new Array,i=new Array,r=s.add(()=>{const a=e.length;for(let o=0;o{e.push(a),t.push(o),i.push(l)},dispose:()=>{s.remove(r)}}}Ae.prototype.runCoroutineAsync=function(s){if(!this._coroutineScheduler){const e=fPt(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return IJ(s,this._coroutineScheduler)};Ae.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const pPt="equirectangularPanoramaPixelShader",mPt=`#ifdef GL_ES precision highp float; #endif #define M_PI 3.1415926535897932384626433832795 varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( - sin( longitude )*sin( latitude ), cos( latitude ), - cos( longitude )*sin( latitude ) );normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;de.ShadersStore[pPt]=mPt;async function gPt(s,e){var a;const t=e.probe??new cT("tempProbe",e.size,s),i=!!e.probe;i||(e.position?t.position=e.position.clone():s.activeCamera&&(t.position=s.activeCamera.position.clone()));const r=e.meshesFilter?s.meshes.filter(e.meshesFilter):s.meshes;(a=t.renderList)==null||a.push(...r),t.refreshRate=Rs.REFRESHRATE_RENDER_ONCE,t.cubeTexture.render();const n=new WKe("tempProceduralTexture","equirectangularPanorama",{width:e.size*2,height:e.size},s);return n.setTexture("cubeMap",t.cubeTexture),new Promise((o,l)=>{n.onGeneratedObservable.addOnce(()=>{const c=n.readPixels();if(!c){l(new Error("No Pixel Data found on procedural texture")),n.dispose(),i||t.dispose();return}c.then(u=>{n.dispose(),i||t.dispose(),e.filename?(e6(e.size*2,e.size,u,void 0,"image/png",e.filename),o(null)):o(u)})})})}class _Pt{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t==null||t.throwIfAborted();const i=t?()=>(t.throwIfAborted(),e()):e,r=this._currentOperation.then(i);return this._currentOperation=new Promise(n=>r.then(()=>n(),n)),r}static async LockAsync(e,t,i){if(i==null||i.throwIfAborted(),t.length===0)return await e();const r=new uS;let n=0;return t.forEach(a=>a.lockAsync(async()=>(n++,n===t.length&&r.resolve(await e()),r.promise),i).catch(o=>r.reject(o))),r.promise}}const qJe="rgbdDecodePixelShader",JJe=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;de.ShadersStore[qJe]=JJe;const eet={name:qJe,shader:JJe},tet=Object.freeze(Object.defineProperty({__proto__:null,rgbdDecodePixelShader:eet},Symbol.toStringTag,{value:"Module"})),iet="rgbdEncodePixelShader",ret=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;de.ShadersStore[iet]=ret;const set={name:iet,shader:ret},vPt=Object.freeze(Object.defineProperty({__proto__:null,rgbdEncodePixelShader:set},Symbol.toStringTag,{value:"Module"})),net="rgbdDecodePixelShader",aet=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`;de.ShadersStoreWGSL[net]=aet;const oet={name:net,shader:aet},cet=Object.freeze(Object.defineProperty({__proto__:null,rgbdDecodePixelShaderWGSL:oet},Symbol.toStringTag,{value:"Module"})),uet="rgbdEncodePixelShader",het=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`;de.ShadersStoreWGSL[uet]=het;const det={name:uet,shader:het},yPt=Object.freeze(Object.defineProperty({__proto__:null,rgbdEncodePixelShaderWGSL:det},Symbol.toStringTag,{value:"Module"})),fet="copyTextureToTexturePixelShader",pet=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; #include void main(void) {vec4 color=texture2D(textureSampler,vUV); #ifdef DEPTH_TEXTURE gl_FragDepth=color.r; #else if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} gl_FragColor=color; #endif } `;de.ShadersStore[fet]=pet;const met={name:fet,shader:pet},xPt=Object.freeze(Object.defineProperty({__proto__:null,copyTextureToTexturePixelShader:met},Symbol.toStringTag,{value:"Module"})),get="copyTextureToTexturePixelShader",_et=`uniform conversion: f32;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f; #include @fragment fn main(input: FragmentInputs)->FragmentOutputs {var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); #ifdef DEPTH_TEXTURE fragmentOutputs.fragDepth=color.r; #else if (uniforms.conversion==1.) {color=toLinearSpaceVec4(color);} else if (uniforms.conversion==2.) {color=toGammaSpace(color);} fragmentOutputs.color=color; #endif } `;de.ShadersStoreWGSL[get]=_et;const vet={name:get,shader:_et},APt=Object.freeze(Object.defineProperty({__proto__:null,copyTextureToTexturePixelShaderWGSL:vet},Symbol.toStringTag,{value:"Module"}));var Qde;(function(s){s[s.ENTERING_XR=0]="ENTERING_XR",s[s.EXITING_XR=1]="EXITING_XR",s[s.IN_XR=2]="IN_XR",s[s.NOT_IN_XR=3]="NOT_IN_XR"})(Qde||(Qde={}));var $de;(function(s){s[s.NOT_TRACKING=0]="NOT_TRACKING",s[s.TRACKING_LOST=1]="TRACKING_LOST",s[s.TRACKING=2]="TRACKING"})($de||($de={}));class Rv extends gl{constructor(e,t={}){super(e),this.options=t,this._direction=new D(0,0,-1),this._mat=new he,this._onSelectEnabled=!1,this._origin=new D(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new Ae,this._onHitTestResults=i=>{const r=i.map(n=>{const a=he.FromArray(n.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||a.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&a.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),a),{xrHitResult:n,transformationMatrix:a}});this.lastNativeXRHitResults=i,this.onHitTestResultObservable.notifyObservers(r)},this._onSelect=i=>{this._onSelectEnabled&&Rv.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Me.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(n=>{const a=r||(o=>!!o.hitMatrix);return n.filter(a)})}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return super.attach()?(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0):!1}detach(){return super.detach()?(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0):!1}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;he.FromArrayToRef(t.transform.matrix,0,this._mat),D.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),D.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});Rv.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}Rv.Name=wr.HIT_TEST;Rv.Version=1;Yn.AddWebXRFeature(Rv.Name,(s,e)=>()=>new Rv(s,e),Rv.Version,!1);let bPt=0;class pP extends gl{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new Ae,this.onAnchorRemovedObservable=new Ae,this.onAnchorUpdatedObservable=new Ae,this._tmpVector=new D,this._tmpQuaternion=new Pe,this.xrNativeFeatureName="anchors",this._options.clearAnchorsOnSessionInit&&this._xrSessionManager.onXRSessionInit.add(()=>{this._trackedAnchors.length=0,this._futureAnchors.length=0,this._lastFrameDetected.clear()})}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new D,i=new Pe){this._populateTmpTransformation(t,i);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{const n=await e.xrHitResult.createAnchor(r);return new Promise((a,o)=>{this._futureAnchors.push({nativeAnchor:n,resolved:!1,submitted:!0,xrTransformation:r,resolve:a,reject:o})})}catch(n){throw new Error(n)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new Pe,i=!1){this._populateTmpTransformation(e,t);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),n=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((a,o)=>{this._futureAnchors.push({nativeAnchor:n,resolved:!1,submitted:!1,xrTransformation:r,resolve:a,reject:o})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();e&&this.onAnchorRemovedObservable.notifyObservers(e)}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter(n=>!t.has(n.xrAnchor)).map(n=>this._trackedAnchors.indexOf(n));let r=0;i.forEach(n=>{const a=this._trackedAnchors.splice(n-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(a),r++}),t.forEach(n=>{if(this._lastFrameDetected.has(n)){const a=this._findIndexInAnchorArray(n),o=this._trackedAnchors[a];try{this._updateAnchorWithXRFrame(n,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new Pe,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(o)}catch{Me.Warn("Anchor could not be updated")}}else{const a={id:bPt++,xrAnchor:n,remove:()=>n.delete()},o=this._updateAnchorWithXRFrame(n,a,e);this._trackedAnchors.push(o),this.onAnchorAddedObservable.notifyObservers(o);const c=this._futureAnchors.filter(u=>u.nativeAnchor===n)[0];c&&(c.resolve(o),c.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(i=>{!i.resolved&&!i.submitted&&(this._createAnchorAtTransformation(i.xrTransformation,e).then(r=>{i.nativeAnchor=r},r=>{i.resolved=!0,i.reject(r)}),i.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new pP(s,e),pP.Version);let CPt=0;class mP extends gl{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new Ae,this.onPlaneRemovedObservable=new Ae,this.onPlaneUpdatedObservable=new Ae,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return typeof XRPlane<"u"}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var i;if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||((i=e.worldInformation)==null?void 0:i.detectedPlanes);if(t){for(let r=0;r{if(this._lastFrameDetected.has(r)){if(r.lastChangedTime===this._xrSessionManager.currentTimestamp){const n=this._findIndexInPlaneArray(r),a=this._detectedPlanes[n];this._updatePlaneWithXRPlane(r,a,e),this.onPlaneUpdatedObservable.notifyObservers(a)}}else{const n={id:CPt++,xrPlane:r,polygonDefinition:[]},a=this._updatePlaneWithXRPlane(r,n,e);this._detectedPlanes.push(a),this.onPlaneAddedObservable.notifyObservers(a)}}),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){e();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(n=>{const a=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new D(n.x,n.y,n.z*a)});const r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){const n=t.transformationMatrix||new he;he.FromArrayToRef(r.transform.matrix,0,n),this._xrSessionManager.scene.useRightHandedSystem||n.toggleModelMatrixHandInPlace(),t.transformationMatrix=n,this._options.worldParentNode&&n.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),n)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new mP(s,e),mP.Version);class gP extends gl{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new Ae}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(i=>i.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}}gP.Name=wr.BACKGROUND_REMOVER;gP.Version=1;Yn.AddWebXRFeature(gP.Name,(s,e)=>()=>new gP(s,e),gP.Version,!0);class SPt{}class _P extends gl{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||oi.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=kc("impostor-mesh-"+e.uniqueId,{diameterX:typeof i=="number"?i:i.width,diameterY:typeof i=="number"?i:i.height,diameterZ:typeof i=="number"?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new Pe;const n=e.grip||e.pointer;r.position.copyFrom(n.position),r.rotationQuaternion.copyFrom(n.rotationQuaternion);const a=new oi(r,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:a,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=i=>{this._controllers[i.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||fe.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&i.inputSource.gamepad?i.onMotionControllerInitObservable.addOnce(r=>{r._doNotLoadControllerMesh?this._createPhysicsImpostor(i):r.onModelLoadedObservable.addOnce(()=>{const n=new oi(r.rootMesh,oi.MeshImpostor,{mass:0,...this._options.physicsProperties}),a=i.grip||i.pointer;this._controllers[i.uniqueId]={xrController:i,impostor:n,oldPos:a.position.clone(),oldRotation:a.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(i))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new Pe,this._tmpVector=new D,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:oi.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=kc("headset-mesh",{diameterX:typeof t=="number"?t:t.width,diameterY:typeof t=="number"?t:t.height,diameterZ:typeof t=="number"?t:t.depth}),this._headsetMesh.rotationQuaternion=new Pe,this._headsetMesh.isVisible=!1,this._headsetImpostor=new oi(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0):!1}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t=typeof e=="string"?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),(t=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&t.linearVelocity){const r=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(r.x,r.y,r.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if((i=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&i.angularVelocity){const r=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(r.x,r.y,r.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(r=>{var c,u;const n=this._controllers[r],a=n.xrController.grip||n.xrController.pointer,o=n.oldPos||n.impostorMesh.position;if((c=n.xrController._lastXRPose)!=null&&c.linearVelocity){const h=n.xrController._lastXRPose.linearVelocity;this._tmpVector.set(h.x,h.y,h.z),n.impostor.setLinearVelocity(this._tmpVector)}else a.position.subtractToRef(o,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),n.impostor.setLinearVelocity(this._tmpVector);o.copyFrom(a.position),this._debugMode&&fe.Log([this._tmpVector,"linear"]);const l=n.oldRotation||n.impostorMesh.rotationQuaternion;if((u=n.xrController._lastXRPose)!=null&&u.angularVelocity){const h=n.xrController._lastXRPose.angularVelocity;this._tmpVector.set(h.x,h.y,h.z),n.impostor.setAngularVelocity(this._tmpVector)}else if(!l.equalsWithEpsilon(a.rotationQuaternion)){l.conjugateInPlace().multiplyToRef(a.rotationQuaternion,this._tmpQuaternion);const h=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),h<.001)this._tmpVector.scaleInPlace(2);else{const d=2*Math.atan2(h,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(d/(h*(this._delta/1e3)))}n.impostor.setAngularVelocity(this._tmpVector)}l.copyFrom(a.rotationQuaternion),this._debugMode&&fe.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}_P.Name=wr.PHYSICS_CONTROLLERS;_P.Version=1;Yn.AddWebXRFeature(_P.Name,(s,e)=>()=>new _P(s,e),_P.Version,!0);class vP extends gl{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new he,this._tmpPos=new D,this._tmpQuat=new Pe,this._initHitTestSource=i=>{if(!i)return;const r=new XRRay(this.options.offsetRay||{}),n={space:this.options.useReferenceSpace?i:this._xrSessionManager.viewerReferenceSpace,offsetRay:r};if(this.options.entityTypes&&(n.entityTypes=this.options.entityTypes),!n.space){Me.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(n).then(a=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=a})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new Ae,this.paused=!1,this.xrNativeFeatureName="hit-test",Me.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(t=>{this._transientXrHitTestSource=t})}return!0}detach(){return super.detach()?(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0):!1}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!(!this.attached||this.paused)){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach(i=>{this._processWebXRHitTestResult(i.results,i.inputSource)})}}_processWebXRHitTestResult(e,t){const i=[];e.forEach(r=>{const n=r.getPose(this._xrSessionManager.referenceSpace);if(!n)return;const a=n.transform.position,o=n.transform.orientation;this._tmpPos.set(a.x,a.y,a.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(o.x,o.y,o.z,o.w),he.FromFloat32ArrayToRefScaled(n.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const l={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:r};i.push(l)}),this.onHitTestResultObservable.notifyObservers(i)}}vP.Name=wr.HIT_TEST;vP.Version=2;Yn.AddWebXRFeature(vP.Name,(s,e)=>()=>new vP(s,e),vP.Version,!1);class yP extends gl{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new Ae,this.onFeaturePointsUpdatedObservable=new Ae,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return super.detach()?(this.featurePointCloud.length=0,!0):!1}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(!(!t||t.length===0)){if(t.length%5!==0)throw new Error("Received malformed feature point cloud of length: "+t.length);const i=t.length/5,r=[],n=[];for(let a=0;a0&&this.onFeaturePointsAddedObservable.notifyObservers(n),r.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(r)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}yP.Name=wr.FEATURE_POINTS;yP.Version=1;Yn.AddWebXRFeature(yP.Name,s=>()=>new yP(s),yP.Version);let EPt=0;class xP extends gl{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new Ae,this.onMeshRemovedObservable=new Ae,this.onMeshUpdatedObservable=new Ae,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return super.detach()?(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0):!1}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;const i=e.detectedMeshes||((t=e.worldInformation)==null?void 0:t.detectedMeshes);if(i){const r=new Set;this._detectedMeshes.forEach((n,a)=>{i.has(a)||r.add(a)}),r.forEach(n=>{const a=this._detectedMeshes.get(n);a&&(this.onMeshRemovedObservable.notifyObservers(a),this._detectedMeshes.delete(n))}),i.forEach(n=>{if(this._detectedMeshes.has(n)){if(n.lastChangedTime===this._xrSessionManager.currentTimestamp){const a=this._detectedMeshes.get(n);a&&(this._updateVertexDataWithXRMesh(n,a,e),this.onMeshUpdatedObservable.notifyObservers(a))}}else{const a={id:EPt++,xrMesh:n},o=this._updateVertexDataWithXRMesh(n,a,e);this._detectedMeshes.set(n,o),this.onMeshAddedObservable.notifyObservers(o)}})}}catch(i){fe.Log(i.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){var n;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const r=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=r,t.normals=e.normals;else{t.positions=new Float32Array(r.length);for(let o=0;o()=>new xP(s,e),xP.Version,!1);var x1;(function(s){s[s.NotReceived=0]="NotReceived",s[s.Waiting=1]="Waiting",s[s.Received=2]="Received"})(x1||(x1={}));class AP extends gl{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new Ae,this.onTrackableImageFoundObservable=new Ae,this.onTrackedImageUpdatedObservable=new Ae,this._trackableScoreStatus=x1.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map(t=>typeof t.src=="string"?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(t.src):Promise.resolve(t.src));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map((i,r)=>({image:i,widthInMeters:this.options.images[r].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch{return Me.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===x1.Waiting)return;if(this._trackableScoreStatus===x1.NotReceived){this._checkScoresAsync();return}const t=e.getImageTrackingResults();for(const i of t){let r=!1;const n=i.index,a=this._trackedImages[n];if(!a)continue;a.xrTrackingResult=i,a.realWorldWidth!==i.measuredWidthInMeters&&(a.realWorldWidth=i.measuredWidthInMeters,r=!0);const o=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(o){const u=a.transformationMatrix;he.FromArrayToRef(o.transform.matrix,0,u),this._xrSessionManager.scene.useRightHandedSystem||u.toggleModelMatrixHandInPlace(),r=!0}const c=i.trackingState==="emulated";a.emulated!==c&&(a.emulated=c,r=!0),r&&this.onTrackedImageUpdatedObservable.notifyObservers(a)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==x1.NotReceived)return;this._trackableScoreStatus=x1.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=x1.NotReceived;return}for(let t=0;t0?x1.Received:x1.NotReceived}}AP.Name=wr.IMAGE_TRACKING;AP.Version=1;Yn.AddWebXRFeature(AP.Name,(s,e)=>()=>new AP(s,e),AP.Version,!1);class bP extends gl{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Me.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!super.attach()||!this._xrSessionManager.session.domOverlayState||this._xrSessionManager.session.domOverlayState.type===null?!1:(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,this._element!==null&&this.options.supressXRSelectEvents===!0&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),this._element!==null&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(this.options.element===void 0)return Me.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if(typeof this.options.element=="string"){const e=document.querySelector(this.options.element);if(e===null)return Me.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}bP.Name=wr.DOM_OVERLAY;bP.Version=1;Yn.AddWebXRFeature(bP.Name,(s,e)=>()=>new bP(s,e),bP.Version,!1);class Iv extends gl{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new Pe,this._tmpRotationMatrix=he.Identity(),this._tmpTranslationDirection=new D,this._tmpMovementTranslation=new D,this._tempCacheQuaternion=new Pe,this._attachController=i=>{if(this._controllers[i.uniqueId])return;this._controllers[i.uniqueId]={xrController:i,registeredComponents:[]};const r=this._controllers[i.uniqueId];if(r.xrController.inputSource.targetRayMode==="tracked-pointer"&&r.xrController.inputSource.gamepad){const n=()=>{if(i.motionController)for(const a of this._currentRegistrationConfigurations){let o=null;if(a.allowedComponentTypes)for(const c of a.allowedComponentTypes){const u=i.motionController.getComponentOfType(c);if(u!==null){o=u;break}}if(a.mainComponentOnly){const c=i.motionController.getMainComponent();if(c===null)continue;o=c}if(typeof a.componentSelectionPredicate=="function"&&(o=a.componentSelectionPredicate(i)),o&&a.forceHandedness&&i.inputSource.handedness!==a.forceHandedness||o===null)continue;const l={registrationConfiguration:a,component:o};r.registeredComponents.push(l),"axisChangedHandler"in a&&(l.onAxisChangedObserver=o.onAxisValueChangedObservable.add(c=>{a.axisChangedHandler(c,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedHandler"in a&&(l.onButtonChangedObserver=o.onButtonStateChangedObservable.add(c=>{c.changes.pressed&&a.buttonChangedHandler(c.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};i.motionController?n():i.onMotionControllerInitObservable.addOnce(()=>{n()})}},!t||t.xrInput===void 0){Me.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Iv.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementOrientationFollowsController:t.movementOrientationFollowsController??!1,orientationPreferredHandedness:t.orientationPreferredHandedness,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return super.attach()?(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0):!1}_onXRFrame(e){if(this.attached){if(this._movementState.rotateX!==0&&this._featureContext.rotationEnabled){const i=this._xrSessionManager.scene.getEngine().getDeltaTime()*.001*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);if(this._featureContext.movementOrientationFollowsViewerPose)this._xrInput.xrCamera.cameraRotation.y+=i,Pe.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection);else if(this._featureContext.movementOrientationFollowsController){this._xrInput.xrCamera.cameraRotation.y+=i;const r=this._featureContext.orientationPreferredHandedness||"right",n=Object.keys(this._controllers).find(o=>{var l,c;return((c=(l=this._controllers[o])==null?void 0:l.xrController)==null?void 0:c.inputSource.handedness)===r})||Object.keys(this._controllers)[0],a=this._controllers[n];Pe.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),((a==null?void 0:a.xrController.pointer.rotationQuaternion)||Pe.Identity()).multiplyToRef(this._tempCacheQuaternion,this._movementDirection)}else Pe.RotationYawPitchRollToRef(i*3,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion)}else if(this._featureContext.movementOrientationFollowsViewerPose)this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);else if(this._featureContext.movementOrientationFollowsController){const t=this._featureContext.orientationPreferredHandedness||"right",i=Object.keys(this._controllers).find(n=>{var a;return((a=this._controllers[n])==null?void 0:a.xrController.inputSource.handedness)===t})||Object.keys(this._controllers)[0],r=this._controllers[i];this._movementDirection.copyFrom((r==null?void 0:r.xrController.pointer.rotationQuaternion)||Pe.Identity())}(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(he.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),D.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const i of t.registeredComponents)i.onAxisChangedObserver&&i.component.onAxisValueChangedObservable.remove(i.onAxisChangedObserver),i.onButtonChangedObserver&&i.component.onButtonStateChangedObservable.remove(i.onButtonChangedObserver);delete this._controllers[e]}}}Iv.Name=wr.MOVEMENT;Iv.REGISTRATIONS={default:[{allowedComponentTypes:[id.THUMBSTICK_TYPE,id.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(s,e,t)=>{e.rotateX=Math.abs(s.x)>t.rotationThreshold?s.x:0,e.rotateY=Math.abs(s.y)>t.rotationThreshold?s.y:0}},{allowedComponentTypes:[id.THUMBSTICK_TYPE,id.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(s,e,t)=>{e.moveX=Math.abs(s.x)>t.movementThreshold?s.x:0,e.moveY=Math.abs(s.y)>t.movementThreshold?s.y:0}}]};Iv.Version=1;Yn.AddWebXRFeature(Iv.Name,(s,e)=>()=>new Iv(s,e),Iv.Version,!0);class CP extends gl{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=D.Up().negateInPlace(),this._lightColor=Re.White(),this._intensity=1,this._sphericalHarmonics=new bx,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new Ae,this._updateReflectionCubeMap=()=>{var r;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const n=Date.now();if(n-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)}))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new dc("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new D(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Us.FALLOFF_GLTF),this._hdrFilter=new K1e(this._xrSessionManager.scene.getEngine()),Me.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return this._canvasContext===null&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(this._xrWebGLBinding===null){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then(t=>{this._xrLightProbe=t,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new $r(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){const e=super.detach();return this._xrLightProbe!==null&&!this.options.disableCubeMapReflection&&(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),this._reflectionCubeMap!==null&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(this._xrLightProbe!==null){if(this.options.lightEstimationPollInterval){const i=Date.now();if(i-this._lightEstimationPollTime()=>new CP(s,e),CP.Version,!1);class SP extends gl{constructor(e){super(e),this.onEyeTrackingStartedObservable=new Ae,this.onEyeTrackingEndedObservable=new Ae,this.onEyeTrackingFrameUpdateObservable=new Ae,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new $i(D.Zero(),D.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(!(!this.attached||!e)&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const i=t.transform.orientation;se.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?D.RightHandedForwardReadOnly.rotateByQuaternionToRef(se.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,se.Quaternion[0].z*=-1,se.Quaternion[0].w*=-1,D.LeftHandedForwardReadOnly.rotateByQuaternionToRef(se.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}SP.Name=wr.EYE_TRACKING;SP.Version=1;Yn.AddWebXRFeature(SP.Name,s=>()=>new SP(s),SP.Version,!1);class TPt{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class MPt{constructor(){this._samples=new TPt(20),this._entropy=0,this.onFirstStepDetected=new Ae}update(e,t,i,r){this._samples.push(e,t);const n=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=we.Distance(n,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let a;for(a=this._samePointCheckStartIdx;ao&&(l=A,o=x);if(oa*this._squaredProjectionDistanceThreshold)return;const m=se.Vector3[0];m.set(i,r,0);const g=se.Vector3[1];g.set(u.x,u.y,0);const _=D.Cross(m,g).z>0,y=n.clone(),v=n.clone();c.subtractToRef(n,u),_?(u.scaleAndAddToRef(this._axisToApexShrinkFactor,y),u.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(u.scaleAndAddToRef(this._axisToApexExtendFactor,y),u.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:y,rightApex:v,currentPosition:n,currentStepDirection:_?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}}class QB{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new MPt,this._walker=null,this._movement=new we,this._millisecondsSinceLastUpdate=QB._MillisecondsPerUpdate,this.movementThisFrame=D.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new RPt(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{fe.Log("Footfall!")}),this._walker.onMovement.add(i=>{this._walker.forward.scaleAndAddToRef(.024*i.deltaT,this._movement)}))})}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=QB._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=QB._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class r$ extends gl{static get Name(){return wr.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera=this._locomotionTarget.getClassName()==="WebXRCamera"}constructor(e,t){super(e),this._up=new D,this._forward=new D,this._position=new D,this._movement=new D,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&fe.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return this._sessionManager.sessionMode===void 0||this._sessionManager.sessionMode==="immersive-vr"}attach(){return!this.isCompatible||!super.attach()?!1:(this._walker=new QB(this._sessionManager.scene.getEngine()),!0)}detach(){return super.detach()?(this._walker=null,!0):!1}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||D.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}Yn.AddWebXRFeature(r$.Name,(s,e)=>()=>new r$(s,e),r$.Version,!1);class yet extends jge{constructor(e,t,i,r,n,a,o=null){super(e,t,i,r,a),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=n,this.createRTTProvider=a,this._originalInternalTexture=o}}class xet extends KJ{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new Ae,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),r=t=="right"?1:0,n=e.colorTextureWidth??e.textureWidth,a=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[r]||(i==null?void 0:i.textureWidth)!==n||(i==null?void 0:i.textureHeight)!==a){let o;const l=e.depthStencilTextureWidth??n,c=e.depthStencilTextureHeight??a;(n===l||a===c)&&(o=e.depthStencilTexture),this._renderTargetTextures[r]=this._createRenderTargetTexture(n,a,null,e.colorTexture,o,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:n,framebufferHeight:a},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[r],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[r]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e==null?void 0:e.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,r=t.colorTextureHeight??t.textureHeight,n=t.viewport;e.x=n.x/i,e.y=n.y/r,e.width=n.width/i,e.height=n.height/r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class IPt extends yet{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,r=>new PPt(r,i,this)),this.layer=e}}class PPt extends xet{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}}const MMe={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},wPt={};class EP extends gl{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...MMe,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return super.detach()?(this._existingLayers.forEach(e=>{e.dispose()}),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0):!1}createXRWebGLLayer(e=wPt){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Xge(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&e.textureType!=="texture-array")throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&e.textureType==="texture-array")throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=MMe,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),r=new IPt(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(r),r}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,r=this._existingLayers[0].layer.textureHeight,n={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:r,clearOnAccess:!0,...e.params};this._validateLayerInit(n,!1);const a=this._xrWebGLBinding.createQuadLayer(n);a.width=this._isMultiviewEnabled?1:2,a.height=1;const o=new yet(()=>a.width,()=>a.height,a,"XRQuadLayer",!1,c=>new xet(c,this._xrWebGLBinding,o));t&&this._compositionLayerTextureMapping.set(a,t);const l=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(a,l),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),r=i.layer,a={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)},o={x:0,y:0,z:0,w:1};r.transform=new XRRigidTransform(a,o);const l=this._layerToRTTProviderMapping.get(r);if(!l)throw new Error("Could not find the RTT provider for the layer");const c=this._xrSessionManager.scene.layers.find(u=>u.texture===e);if(!c)throw new Error("Could not find the babylon layer for the texture");return l.onRenderTargetTextureCreatedObservable.add(u=>{u.eye&&u.eye==="right"||(u.texture.clearColor=new Ze(0,0,0,0),c.renderTargetTextures.push(u.texture),c.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add(()=>{u.texture.render()}),c.renderTargetTextures.push(u.texture),c.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce(()=>{c.renderTargetTextures.splice(c.renderTargetTextures.indexOf(u.texture),1),c.renderOnlyInRenderTargetTextures=!1}))}),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;const n={x:0,y:0,z:-10},a={x:0,y:0,z:0,w:1};i.transform=new XRRigidTransform(n,a);const o=this._layerToRTTProviderMapping.get(i);if(!o)throw new Error("Could not find the RTT provider for the layer");return o.onRenderTargetTextureCreatedObservable.add(l=>{l.texture.clearColor=new Ze(0,0,0,0),l.texture.customRenderFunction=()=>{e.render()}}),this._xrSessionManager.onXRSessionInit.add(()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)}),this._xrSessionManager.onXRSessionEnded.add(()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)}),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new EP(s,e),EP.Version,!1);class TP extends gl{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new zr(e,0);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format=this.depthDataFormat==="ushort"?2:5,t.generateMipMaps=!1,t.type=this.depthDataFormat==="ushort"?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new tT(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?this.depthDataFormat==="ushort"?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new Ae,this.xrNativeFeatureName="depth-sensing",Me.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!super.attach(e)||this._xrSessionManager.session.depthDataFormat==null||this._xrSessionManager.session.depthUsage==null?!1:(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;(e=this._cachedDepthImageTexture)==null||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(i!=null)for(const r of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,r,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,r,this.depthDataFormat);break;default:Me.Error("Unknown depth usage"),this.detach();break}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(r===null)return;const{data:n,width:a,height:o,rawValueToMeters:l,getDepthInMeters:c}=r;switch(this._width=a,this._height=o,this._rawValueToMeters=l,this._cachedDepthBuffer=n,this.onGetDepthInMetersAvailable.notifyObservers(c.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=yn.CreateRTexture(null,a,o,this._xrSessionManager.scene,!1,!0,xe.NEAREST_SAMPLINGMODE,1)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(n)).map(u=>u*l));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(n).map(u=>u*l));break}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(r===null)return;const{texture:n,width:a,height:o}=r;this._width=a,this._height=o,this._cachedWebGLTexture=n;const l=this._xrSessionManager.scene,u=l.getEngine().wrapWebGLTexture(n);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=yn.CreateRTexture(null,a,o,l,!1,!0,xe.NEAREST_SAMPLINGMODE,i==="ushort"?0:1)),this._cachedDepthImageTexture._texture=u}getXRSessionInitExtension(){const e=this.options.usagePreference!=null&&this.options.usagePreference.length!==0,t=this.options.dataFormatPreference!=null&&this.options.dataFormatPreference.length!==0;return new Promise(i=>{if(e&&t){const r=this.options.usagePreference.map(a=>{switch(a){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),n=this.options.dataFormatPreference.map(a=>{switch(a){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:r,dataFormatPreference:n}})}else i({})})}}TP.Name=wr.DEPTH_SENSING;TP.Version=1;Yn.AddWebXRFeature(TP.Name,(s,e)=>()=>new TP(s,e),TP.Version,!1);const DPt="velocityPixelShader",LPt=`precision highp float; #define CUSTOM_FRAGMENT_BEGIN varying vec4 clipPos;varying vec4 previousClipPos; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; #define CUSTOM_FRAGMENT_MAIN_END }`;de.ShadersStore[DPt]=LPt;const OPt="velocityVertexShader",NPt=`#define CUSTOM_VERTEX_BEGIN #define VELOCITY attribute vec3 position; #include uniform mat4 viewProjection;uniform mat4 previousViewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; #endif varying vec4 clipPos;varying vec4 previousClipPos; #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} #elif clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; #endif #define CUSTOM_VERTEX_MAIN_END }`;de.ShadersStore[OPt]=NPt;class Aet extends Rs{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[he.Identity(),he.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new na("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(n=>{this._previousWorldMatrices[n.uniqueId]=this._previousWorldMatrices[n.uniqueId]||n.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[n.uniqueId]),this._previousWorldMatrices[n.uniqueId]=n.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(r=>{this._originalPairing.push([r,r.material]),r.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(r=>{r[0].material=r[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class bet{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if(t.layerType!=="XRProjectionLayer")throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,n){if(!this._engine)throw new Error("Engine is disposed");const a={width:e,height:t},o=new Aet(r,n,this._scene,a),l=o.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=r,l._depthStencilTextureArray=n,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let r=this._renderTargetTextures.get(t.eye);const n=e.motionVectorTextureWidth,a=e.motionVectorTextureHeight;return(!r||(i==null?void 0:i.textureWidth)!==n||(i==null?void 0:i.textureHeight)!=a)&&(r=this._createRenderTargetTexture(n,a,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:n,framebufferHeight:a}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class MP extends gl{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[wr.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new bet(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}MP.Name=wr.SPACE_WARP;MP.Version=1;Yn.AddWebXRFeature(MP.Name,s=>()=>new MP(s),MP.Version,!1);class RP extends gl{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new Ae,this.xrNativeFeatureName="camera-access"}attach(e){return super.attach(e)?(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0):!1}detach(){return super.detach()?(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach(e=>e.dispose()),this.texturesData.forEach(e=>e.dispose()),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0):!1}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,n=(1-r[8])*i.width/2+i.x,a=(1-r[9])*i.height/2+i.y,o=i.width/2*r[0],l=i.height/2*r[5],c=i.width/2*r[4];this.cameraIntrinsics[t]={u0:n,v0:a,ax:o,ay:l,gamma:c,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var r,n;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=(r=this._glBinding)==null?void 0:r.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(n=this._cachedInternalTextures[t]._hardwareTexture)==null||n.set(i);else{const a=new zr(this._xrSessionManager.scene.getEngine(),0,!0);a.invertY=!1,a.format=5,a.generateMipMaps=!0,a.type=1,a.samplingMode=3,a.width=e.camera.width,a.height=e.camera.height,a._cachedWrapU=1,a._cachedWrapV=1,a._hardwareTexture=new tT(i,this._glContext),this._cachedInternalTextures[t]=a;const o=new $r(this._xrSessionManager.scene);o.name=`WebXR Raw Camera Access (${t})`,o._texture=this._cachedInternalTextures[t],this.texturesData[t]=o,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let r=!0;i.views.forEach((n,a)=>{r=r&&this._updateInternalTextures(n,a)}),r&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}RP.Name=wr.RAW_CAMERA_ACCESS;RP.Version=1;Yn.AddWebXRFeature(RP.Name,(s,e)=>()=>new RP(s,e),RP.Version,!1);class Cet extends lT{constructor(e,t,i){super(e,FPt[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}ll.RegisterController("generic-hand-select-grasp",(s,e)=>new Cet(e,s.gamepad,s.handedness));const FPt={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class Pv extends lT{constructor(e,t,i){super(e,BPt["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=Pv.MODEL_LEFT_FILENAME:e=Pv.MODEL_RIGHT_FILENAME;const i=Pv.MODEL_BASE_URL+"default"+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=Ys.IsPluginForExtensionAvailable(".glb");return e||fe.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((t,i)=>{if(!this.disableAnimation&&t&&this.rootMesh){const r=this._mapping.buttons[t],n=r.rootNodeName;if(!n){fe.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const a=this._getChildByName(this.rootMesh,n);if(!a){fe.Warn("Missing button mesh with name: "+n);return}if(r.valueMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.valueNodeName),r.pressedMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.pressedNodeName),r.unpressedMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.unpressedNodeName),r.valueMesh&&r.pressedMesh&&r.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(l=>{this._lerpTransform(r,l.value)},void 0,!0)}else fe.Warn("Missing button submesh under mesh with name: "+n)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);i.isAxes()&&["x-axis","y-axis"].forEach(r=>{if(!this.rootMesh)return;const n=this._mapping.axes[t][r],a=this._getChildByName(this.rootMesh,n.rootNodeName);if(!a){fe.Warn("Missing axis mesh with name: "+n.rootNodeName);return}n.valueMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.valueNodeName),n.minMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.minNodeName),n.maxMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.maxNodeName),n.valueMesh&&n.minMesh&&n.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const l=r==="x-axis"?o.x:o.y;this._lerpTransform(n,l,!0)},void 0,!0):fe.Warn("Missing axis submesh under mesh with name: "+n.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new Ee(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew Pv(e,s.gamepad,s.handedness));const BPt={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class m0 extends lT{constructor(e,t,i,r=!1,n=!1){super(e,kPt[i],t,i),this._forceLegacyControllers=n,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=m0.MODEL_LEFT_FILENAME:e=m0.MODEL_RIGHT_FILENAME;const t=this._isQuest()?m0.QUEST_MODEL_BASE_URL:m0.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i=this.handedness==="right"?-1:1;this.getComponentIds().forEach(r=>{const n=r&&this.getComponent(r);n&&n.onButtonStateChangedObservable.add(a=>{if(!(!this.rootMesh||this.disableAnimation))switch(r){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-a.value*.2,this._modelRootNode.getChildren()[3].position.y=-a.value*.005,this._modelRootNode.getChildren()[3].position.z=-a.value*.005);return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*a.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(a.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(a.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Ee(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Pe.FromEulerAngles(0,Math.PI,0)),e.forEach(t=>{t.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}m0.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";m0.MODEL_LEFT_FILENAME="left.babylon";m0.MODEL_RIGHT_FILENAME="right.babylon";m0.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";ll.RegisterController("oculus-touch",(s,e)=>new m0(e,s.gamepad,s.handedness));ll.RegisterController("oculus-touch-legacy",(s,e)=>new m0(e,s.gamepad,s.handedness,!0));const kPt={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class u6 extends lT{constructor(e,t,i){super(e,UPt[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=u6.MODEL_FILENAME,t=u6.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=t&&this.getComponent(t);i&&i.onButtonStateChangedObservable.add(r=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-r.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Ee(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Pe.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}u6.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";u6.MODEL_FILENAME="wand.babylon";ll.RegisterController("htc-vive",(s,e)=>new u6(e,s.gamepad,s.handedness));const UPt={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class Eet{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}Uke("NativeXRFrame",Eet);var Zde;(function(s){s[s.Input=0]="Input",s[s.Output=1]="Output"})(Zde||(Zde={}));class RZ{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=gh(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=Me.Instantiate(e.className),r=new i(e.name,e._connectionType,t);return r.deserialize(e),r}}class Ka{constructor(e){this.value=this._toInt(e)}_toInt(e){return e|0}add(e){return new Ka(this.value+e.value)}subtract(e){return new Ka(this.value-e.value)}multiply(e){return new Ka(Math.imul(this.value,e.value))}divide(e){return new Ka(this.value/e.value)}getClassName(){return Ka.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Ka(e.value)}}Ka.ClassName="FlowGraphInteger";ve("FlowGraphInteger",Ka);class Rh{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Rh(e.typeName,e.defaultValue)}}const Ot=new Rh("any",void 0),Tet=new Rh("string",""),Js=new Rh("number",0),Ll=new Rh("boolean",!1),IZ=new Rh("Vector2",we.Zero()),i_=new Rh("Vector3",D.Zero()),Met=new Rh("Vector4",mt.Zero()),wv=new Rh("Matrix",he.Identity()),Ret=new Rh("Color3",Re.Black()),Iet=new Rh("Color4",new Ze(0,0,0,0)),Pet=new Rh("Quaternion",Pe.Identity()),La=new Rh("FlowGraphInteger",new Ka(0));function wet(s){switch(typeof s){case"string":return Tet;case"number":return Js;case"boolean":return Ll;case"object":return s instanceof we?IZ:s instanceof D?i_:s instanceof mt?Met:s instanceof Re?Ret:s instanceof Ze?Iet:s instanceof Pe?Pet:s instanceof Ka?La:Ot;default:return Ot}}class PZ extends RZ{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===0}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===1?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=RZ.Parse(e,t);return i.richType=Rh.Parse(e.richType),i}}ve("FGDataConnection",PZ);function Det(s){return s==="Mesh"||s==="AbstractMesh"||s==="GroundMesh"||s==="InstanceMesh"||s==="LinesMesh"||s==="GoldbergMesh"||s==="GreasedLineMesh"||s==="TrailMesh"}function Let(s){return s==="Vector2"||s==="Vector3"||s==="Vector4"||s==="Quaternion"||s==="Color3"||s==="Color4"}function zPt(s,e){if(s==="Vector2")return we.FromArray(e);if(s==="Vector3")return D.FromArray(e);if(s==="Vector4")return mt.FromArray(e);if(s==="Quaternion")return Pe.FromArray(e);if(s==="Color3")return new Re(e[0],e[1],e[2]);if(s==="Color4")return new Ze(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${s}`)}function Z_e(s,e,t){var r;const i=((r=e==null?void 0:e.getClassName)==null?void 0:r.call(e))??"";Det(i)?t[s]={name:e.name,className:i}:Let(i)?t[s]={value:e.asArray(),className:i}:t[s]=e}function Yee(s,e,t){const i=e[s];let r;const n=i==null?void 0:i.className;return Det(n)?r=t.getMeshByName(i.name):Let(n)?r=zPt(n,i.value):n==="Matrix"?r=he.FromArray(i.value):n===Ka.ClassName?r=Ka.Parse(i):i&&i.value!==void 0?r=i.value:r=i,r}function VPt(s){return s==="FGSetPropertyBlock"||s==="FGGetPropertyBlock"||s==="FGPlayAnimationBlock"||s==="FGMeshPickEventBlock"}class o3{constructor(e){var t;this.config=e,this.uniqueId=gh(),this.name=((t=this.config)==null?void 0:t.name)??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new PZ(e,0,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new PZ(e,1,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find(t=>t.name===e)}getDataOutput(e){return this.dataOutputs.find(t=>t.name===e)}serialize(e={},t=Z_e){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const i of this.dataInputs){const r={};i.serialize(r),e.dataInputs.push(r)}for(const i of this.dataOutputs){const r={};i.serialize(r),e.dataOutputs.push(r)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Me.Instantiate(e.className),r={},n=t.valueParseFunction??Yee;if(e.config)for(const o in e.config)r[o]=n(o,e.config,t.scene);VPt(e.className)&&(r.pathConverter=t.pathConverter);const a=new i(r);a.uniqueId=e.uniqueId;for(let o=0;ot.name===e)}getSignalOutput(e){return this.signalOutputs.find(t=>t.name===e)}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{var a,o,l;n.type===yt.POINTERPICK&&((a=n.pickInfo)!=null&&a.pickedMesh)&&(((o=n.pickInfo)==null?void 0:o.pickedMesh)===i||J_e((l=n.pickInfo)==null?void 0:l.pickedMesh,i))&&this._execute(e)});const r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return h6.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}h6.ClassName="FGMeshPickEventBlock";ve(h6.ClassName,h6);var qde;(function(s){s[s.Stopped=0]="Stopped",s[s.Started=1]="Started"})(qde||(qde={}));class d6{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=0,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){const e=new DZ({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==1){this.state=1,this._executionContexts.length===0&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===h6.ClassName){const i=t._getReferencedMesh();let r=0;for(;r0;){const r=t.pop();e(r);for(const n of r.dataInputs)for(const a of n._connectedPoint)i.has(a._ownerBlock.uniqueId)||(t.push(a._ownerBlock),i.add(a._ownerBlock.uniqueId));if(r instanceof rg)for(const n of r.signalOutputs)for(const a of n._connectedPoint)i.has(a._ownerBlock.uniqueId)||(t.push(a._ownerBlock),i.add(a._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks(i=>{const r={};i.serialize(r),e.allBlocks.push(r)}),e.executionContexts=[];for(const i of this._executionContexts){const r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const r of i.dataOutputs)if(r.uniqueId===t)return r;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof rg){for(const r of i.signalInputs)if(r.uniqueId===t)return r}throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),r=[],n=t.valueParseFunction??Yee;for(const a of e.allBlocks){const o=o3.Parse(a,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:n});r.push(o),o instanceof dD&&i.addEventBlock(o)}for(const a of r){for(const o of a.dataInputs)for(const l of o.connectedPointIds){const c=d6.GetDataOutConnectionByUniqueId(r,l);o.connectTo(c)}if(a instanceof rg)for(const o of a.signalOutputs)for(const l of o.connectedPointIds){const c=d6.GetSignalInConnectionByUniqueId(r,l);o.connectTo(c)}}for(const a of e.executionContexts)DZ.Parse(a,{graph:i,valueParseFunction:n});return i}}class OS{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(OS.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new d6({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);t!==-1&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){this._flowGraphs.forEach(i=>i.dispose()),this._flowGraphs.length=0;const e=OS.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);t!==-1&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{const r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t){var n;const i=t.valueParseFunction??Yee,r=new OS({scene:t.scene});return(n=e._flowGraphs)==null||n.forEach(a=>{d6.Parse(a,{coordinator:r,valueParseFunction:i,pathConverter:t.pathConverter})}),r}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new Ae,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}OS.SceneCoordinators=new Map;class GPt{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add(t=>{Me.Log(`Node executed: ${t.getClassName()}`)})}}class lp extends rg{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class f6 extends lp{constructor(e){super(e),this.message=this.registerDataInput("message",Ot)}_execute(e){const t=this.message.getValue(e);fe.Log(t),this.out._activateSignal(e)}getClassName(){return f6.ClassName}}f6.ClassName="FGConsoleLogBlock";ve(f6.ClassName,f6);class p6 extends lp{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Ot)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return p6.ClassName}}p6.ClassName="FGSetVariableBlock";ve(p6.ClassName,p6);const RMe=new RegExp(/\{(\w+)\}/g);class LZ{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=RMe.exec(e);for(;i;){const[,r]=i;this.templatedInputs.push(t.registerDataInput(r,La)),i=RMe.exec(e)}}getAccessor(e,t){let i=this.path;for(const r of this.templatedInputs){const n=r.getValue(t).value;i=i.replace(`{${r.name}}`,n.toString())}return e.convert(i)}}class fD extends lp{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Ot),this.templateComponent=new LZ(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return fD.ClassName}}fD.ClassName="FGSetPropertyBlock";ve("FGSetPropertyBlock",fD);class pD extends lp{constructor(e){super(e),this.config=e;for(let t=0;tr.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return pD.ClassName}}pD.ClassName="FGSendCustomEventBlock";ve("FGSendCustomEventBlock",pD);class Oet extends rg{constructor(e){super(e),this.condition=this.registerDataInput("condition",Ll),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}ve("FGBranchBlock",Oet);class m6 extends lp{constructor(e={startIndex:new Ka(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",La),this.value=this.registerDataOutput("value",La)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);i.valuer)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",n);else{const a=r-(n-i);this.timeRemaining.setValue(a,e)}}getClassName(){return"FGThrottleBlock"}}ve("FGThrottleBlock",Fet);class mD extends q_e{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",Js)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(t!==void 0&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,n=new yUe({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(n,e)});n.start(),i.push(n),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);r!==-1?i.splice(r,1):Me.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const i of t)i.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return mD.ClassName}}mD.ClassName="FGTimerBlock";ve("FGTimerBlock",mD);class Bet extends rg{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",Js),this.config.startIndex=this.config.startIndex!==void 0?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let t=0;t=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(r=r.filter(a=>a!==n),r.length===0)for(let a=0;a=0&&(i[r+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(r=>r)){this.out._activateSignal(e);for(let r=0;r=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}ve("FGDebounceBlock",Vet);class Get extends rg{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Ll)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}ve("FGFlipFlopBlock",Get);class _6 extends rg{constructor(e){super(e),this.config=e,this.outFlows=[];for(let t=0;tthis._onAnimationEnd(c,e));this.runningAnimatable.setValue(c,e),a.push(c)}e._setExecutionVariable(this,"runningAnimatables",a)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],r=i.indexOf(e);r!==-1&&i.splice(r,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const i of t)i.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return _w.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}_w.ClassName="FGPlayAnimationBlock";ve(_w.ClassName,_w);class Wet extends lp{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Ot)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}ve("FGStopAnimationBlock",Wet);class Ket extends lp{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Ot)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}ve("FGPauseAnimationBlock",Ket);class Het extends o3{constructor(e){super(e),this.condition=this.registerDataInput("condition",Ll),this.trueValue=this.registerDataInput("trueValue",Ot),this.falseValue=this.registerDataInput("falseValue",Ot),this.output=this.registerDataOutput("output",Ot)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}ve("FGConditionalDataBlock",Het);class v6 extends o3{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Ot)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return v6.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}v6.ClassName="FGGetVariableBlock";ve(v6.ClassName,v6);class jet extends o3{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Ot),this.destinationSystem=this.registerDataInput("destinationSystem",Ot),this.inputCoordinates=this.registerDataInput("inputCoordinates",i_),this.outputCoordinates=this.registerDataOutput("outputCoordinates",i_)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),n=t.getWorldMatrix(),a=i.getWorldMatrix(),o=se.Matrix[0].copyFrom(a);o.invert();const l=se.Matrix[1];o.multiplyToRef(n,l);const c=this.outputCoordinates.getValue(e);D.TransformCoordinatesToRef(r,l,c)}getClassName(){return"FGCoordinateTransformBlock"}}ve("FGCoordinateTransformBlock",jet);class Xet extends o3{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",wet(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=Z_e){super.serialize(e),t("value",this.config.value,e.config)}}ve("FGConstantBlock",Xet);class y6 extends o3{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Ot),this.templateComponent=new LZ(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return y6.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}y6.ClassName="FGGetPropertyBlock";ve(y6.ClassName,y6);const IMe="cachedOperationValue",PMe="cachedExecutionId";class Qee extends o3{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,PMe),i=e._getExecutionVariable(this,IMe);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const r=this._doOperation(e);e._setExecutionVariable(this,IMe,r),e._setExecutionVariable(this,PMe,e.executionId),this.value.setValue(r,e)}}}class Lo extends Qee{constructor(e,t,i,r,n,a){super(i,a),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Ns extends Qee{constructor(e,t,i,r,n){super(t,n),this._operation=i,this._className=r,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const gD="FGLogic",Yet="AndBlock",Qet="OrBlock",$et="NotBlock";class Zet extends Lo{constructor(e){super(Ll,Ll,Ll,(t,i)=>t&&i,`${gD}${Yet}`,e)}}ve(`${gD}${Yet}`,Zet);class qet extends Lo{constructor(e){super(Ll,Ll,Ll,(t,i)=>t||i,`${gD}${Qet}`,e)}}ve(`${gD}${Qet}`,qet);class Jet extends Ns{constructor(e){super(Ll,Ll,t=>!t,`${gD}${$et}`,e)}}ve(`${gD}${$et}`,Jet);class hV extends Qee{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class e2e extends Qee{constructor(e,t,i,r,n,a,o){super(r,o),this._operation=n,this._className=a,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function mc(s){return s.getClassName?s.getClassName():""}function dV(s,e){return s==="Vector2"&&e==="Vector2"||s==="Vector3"&&e==="Vector3"||s==="Vector4"&&e==="Vector4"}function fV(s,e){return s==="Matrix"&&e==="Matrix"}function pV(s,e){return s==="FlowGraphInteger"&&e==="FlowGraphInteger"}class x6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicAdd(t,i),x6.ClassName,e)}_polymorphicAdd(e,t){const i=mc(e),r=mc(t);return dV(i,r)||fV(i,r)||pV(i,r)?e.add(t):e+t}}x6.ClassName="FGAddBlock";ve(x6.ClassName,x6);class A6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicAdd(t,i),A6.ClassName,e)}_polymorphicAdd(e,t){const i=mc(e),r=mc(t);return dV(i,r)||pV(i,r)?e.subtract(t):fV(i,r)?e.add(t.scale(-1)):e-t}}A6.ClassName="FGSubBlock";ve(A6.ClassName,A6);class b6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicMultiply(t,i),b6.ClassName,e)}_polymorphicMultiply(e,t){const i=mc(e),r=mc(t);return dV(i,r)||pV(i,r)?e.multiply(t):fV(i,r)?he.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}b6.ClassName="FGMultiplyBlock";ve(b6.ClassName,b6);class C6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicDivide(t,i),C6.ClassName,e)}_polymorphicDivide(e,t){const i=mc(e),r=mc(t);return dV(i,r)||pV(i,r)?e.divide(t):fV(i,r)?he.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}C6.ClassName="FGDivideBlock";ve(C6.ClassName,C6);class S6 extends hV{constructor(e){super(Js,()=>Math.random(),S6.ClassName,e)}}S6.ClassName="FGRandomBlock";ve(S6.ClassName,S6);class E6 extends Lo{constructor(e){super(Ot,Ot,Js,(t,i)=>this._polymorphicDot(t,i),E6.ClassName,e)}_polymorphicDot(e,t){switch(mc(e)){case"Vector2":return we.Dot(e,t);case"Vector3":return D.Dot(e,t);case"Vector4":return mt.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}E6.ClassName="FGDotBlock";ve(E6.ClassName,E6);class T6 extends hV{constructor(e){super(Js,()=>Math.E,T6.ClassName,e)}}T6.ClassName="FGEBlock";ve(T6.ClassName,T6);class M6 extends hV{constructor(e){super(Js,()=>Math.PI,M6.ClassName,e)}}M6.ClassName="FGPIBlock";ve(M6.ClassName,M6);class R6 extends hV{constructor(e){super(Js,()=>Number.POSITIVE_INFINITY,R6.ClassName,e)}}R6.ClassName="FGInfBlock";ve(R6.ClassName,R6);class I6 extends hV{constructor(e){super(Js,()=>Number.NaN,I6.ClassName,e)}}I6.ClassName="FGNaNBlock";ve(I6.ClassName,I6);function Fa(s,e){switch(mc(s)){case"FlowGraphInteger":return new Ka(e(s.value));case"Vector2":return new we(e(s.x),e(s.y));case"Vector3":return new D(e(s.x),e(s.y),e(s.z));case"Vector4":return new mt(e(s.x),e(s.y),e(s.z),e(s.w));case"Matrix":return he.FromValues(e(s.m[0]),e(s.m[4]),e(s.m[8]),e(s.m[12]),e(s.m[1]),e(s.m[5]),e(s.m[9]),e(s.m[13]),e(s.m[2]),e(s.m[6]),e(s.m[10]),e(s.m[14]),e(s.m[3]),e(s.m[7]),e(s.m[11]),e(s.m[15]));default:return e(s)}}class P6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicAbs(t),P6.ClassName,e)}_polymorphicAbs(e){return Fa(e,Math.abs)}}P6.ClassName="FGAbsBlock";ve(P6.ClassName,P6);class w6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicSign(t),w6.ClassName,e)}_polymorphicSign(e){return Fa(e,Math.sign)}}w6.ClassName="FGSignBlock";ve(w6.ClassName,w6);class D6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicTrunc(t),D6.ClassName,e)}_polymorphicTrunc(e){return Fa(e,Math.trunc)}}D6.ClassName="FGTruncBlock";ve(D6.ClassName,D6);class L6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicFloor(t),L6.ClassName,e)}_polymorphicFloor(e){return Fa(e,Math.floor)}}L6.ClassName="FGFloorBlock";ve(L6.ClassName,L6);class O6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicCeiling(t),O6.ClassName,e)}_polymorphicCeiling(e){return Fa(e,Math.ceil)}}O6.ClassName="FGCeilBlock";ve(O6.ClassName,O6);class N6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicFract(t),N6.ClassName,e)}_polymorphicFract(e){return Fa(e,t=>t-Math.floor(t))}}N6.ClassName="FGFractBlock";ve(N6.ClassName,N6);class F6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicNeg(t),F6.ClassName,e)}_polymorphicNeg(e){return Fa(e,t=>-t)}}F6.ClassName="FGNegBlock";ve(F6.ClassName,F6);function mV(s,e,t){switch(mc(s)){case"FlowGraphInteger":return new Ka(t(s.value,e.value));case"Vector2":return new we(t(s.x,e.x),t(s.y,e.y));case"Vector3":return new D(t(s.x,e.x),t(s.y,e.y),t(s.z,e.z));case"Vector4":return new mt(t(s.x,e.x),t(s.y,e.y),t(s.z,e.z),t(s.w,e.w));case"Matrix":return he.FromValues(t(s.m[0],e.m[0]),t(s.m[4],e.m[4]),t(s.m[8],e.m[8]),t(s.m[12],e.m[12]),t(s.m[1],e.m[1]),t(s.m[5],e.m[5]),t(s.m[9],e.m[9]),t(s.m[13],e.m[13]),t(s.m[2],e.m[2]),t(s.m[6],e.m[6]),t(s.m[10],e.m[10]),t(s.m[14],e.m[14]),t(s.m[3],e.m[3]),t(s.m[7],e.m[7]),t(s.m[11],e.m[11]),t(s.m[15],e.m[15]));default:return t(s,e)}}class B6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicRemainder(t,i),B6.ClassName,e)}_polymorphicRemainder(e,t){return mV(e,t,(i,r)=>i%r)}}B6.ClassName="FGRemainderBlock";ve(B6.ClassName,B6);class k6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicMin(t,i),k6.ClassName,e)}_polymorphicMin(e,t){return mV(e,t,Math.min)}}k6.ClassName="FGMinBlock";ve(k6.ClassName,k6);class U6 extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicMax(t,i),U6.ClassName,e)}_polymorphicMax(e,t){return mV(e,t,Math.max)}}U6.ClassName="FGMaxBlock";ve(U6.ClassName,U6);function WPt(s,e,t){return Math.min(Math.max(s,Math.min(e,t)),Math.max(e,t))}function ett(s,e,t,i){switch(mc(s)){case"FlowGraphInteger":return new Ka(i(s.value,e.value,t.value));case"Vector2":return new we(i(s.x,e.x,t.x),i(s.y,e.y,t.y));case"Vector3":return new D(i(s.x,e.x,t.x),i(s.y,e.y,t.y),i(s.z,e.z,t.z));case"Vector4":return new mt(i(s.x,e.x,t.x),i(s.y,e.y,t.y),i(s.z,e.z,t.z),i(s.w,e.w,t.w));case"Matrix":return he.FromValues(i(s.m[0],e.m[0],t.m[0]),i(s.m[4],e.m[4],t.m[4]),i(s.m[8],e.m[8],t.m[8]),i(s.m[12],e.m[12],t.m[12]),i(s.m[1],e.m[1],t.m[1]),i(s.m[5],e.m[5],t.m[5]),i(s.m[9],e.m[9],t.m[9]),i(s.m[13],e.m[13],t.m[13]),i(s.m[2],e.m[2],t.m[2]),i(s.m[6],e.m[6],t.m[6]),i(s.m[10],e.m[10],t.m[10]),i(s.m[14],e.m[14],t.m[14]),i(s.m[3],e.m[3],t.m[3]),i(s.m[7],e.m[7],t.m[7]),i(s.m[11],e.m[11],t.m[11]),i(s.m[15],e.m[15],t.m[15]));default:return i(s,e,t)}}class z6 extends e2e{constructor(e){super(Ot,Ot,Ot,Ot,(t,i,r)=>this._polymorphicClamp(t,i,r),z6.ClassName,e)}_polymorphicClamp(e,t,i){return ett(e,t,i,WPt)}}z6.ClassName="FGClampBlock";ve(z6.ClassName,z6);function KPt(s){return Math.min(Math.max(s,0),1)}class V6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicSaturate(t),V6.ClassName,e)}_polymorphicSaturate(e){return Fa(e,KPt)}}V6.ClassName="FGSaturateBlock";ve(V6.ClassName,V6);class G6 extends e2e{constructor(e){super(Ot,Ot,Ot,Ot,(t,i,r)=>this._polymorphicInterpolate(t,i,r),G6.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return ett(e,t,i,this._interpolate)}}G6.ClassName="FGInterpolateBlock";ve(G6.ClassName,G6);class W6 extends Lo{constructor(e){super(Ot,Ot,Ll,(t,i)=>this._polymorphicEq(t,i),W6.ClassName,e)}_polymorphicEq(e,t){const i=mc(e),r=mc(t);return dV(i,r)||fV(i,r)||pV(i,r)?e.equals(t):e===t}}W6.ClassName="FGEqBlock";ve(W6.ClassName,W6);function $ee(s,e,t){const i=mc(s),r=mc(e);if(i===r){if(i==="")return t(s,e);if(i==="FlowGraphInteger")return t(s.value,e.value);throw new Error(`Cannot compare ${s} and ${e}`)}throw new Error(`${s} and ${e} are of different types.`)}class K6 extends Lo{constructor(e){super(Ot,Ot,Ll,(t,i)=>this._polymorphicLessThan(t,i),K6.ClassName,e)}_polymorphicLessThan(e,t){return $ee(e,t,(i,r)=>ithis._polymorphicLessThanOrEqual(t,i),gV.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return $ee(e,t,(i,r)=>i<=r)}}gV.ClassName="FGLessThanOrEqualBlock";class H6 extends Lo{constructor(e){super(Ot,Ot,Ll,(t,i)=>this._polymorphicGreaterThan(t,i),H6.ClassName,e)}_polymorphicGreaterThan(e,t){return $ee(e,t,(i,r)=>i>r)}}H6.ClassName="FGGreaterThanBlock";ve(H6.ClassName,H6);class j6 extends Lo{constructor(e){super(Ot,Ot,Ll,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),j6.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return $ee(e,t,(i,r)=>i>=r)}}j6.ClassName="FGGreaterThanOrEqualBlock";ve(j6.ClassName,j6);class X6 extends Ns{constructor(e){super(Ot,Ll,t=>this._polymorphicIsNan(t),X6.ClassName,e)}_polymorphicIsNan(e){const t=mc(e);if(t==="")return isNaN(e);if(t==="FlowGraphInteger")return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}X6.ClassName="FGIsNanBlock";ve(X6.ClassName,X6);class _V extends Ns{constructor(e){super(Ot,Ll,t=>this._polymorphicIsInf(t),_V.ClassName,e)}_polymorphicIsInf(e){const t=mc(e);if(t==="")return!isFinite(e);if(t==="FlowGraphInteger")return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}_V.ClassName="FGIsInfBlock";class Y6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicDegToRad(t),Y6.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return Fa(e,this._degToRad)}}Y6.ClassName="FGDegToRadBlock";ve(Y6.ClassName,Y6);class Q6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicRadToDeg(t),Q6.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return Fa(e,this._radToDeg)}}Q6.ClassName="FGRadToDegBlock";ve(Q6.ClassName,Q6);class $6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicSin(t),$6.ClassName,e)}_polymorphicSin(e){return Fa(e,Math.sin)}}$6.ClassName="FGSinBlock";ve($6.ClassName,$6);class Z6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicCos(t),Z6.ClassName,e)}_polymorphicCos(e){return Fa(e,Math.cos)}}Z6.ClassName="FGCosBlock";ve(Z6.ClassName,Z6);class q6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicTan(t),q6.ClassName,e)}_polymorphicTan(e){return Fa(e,Math.tan)}}q6.ClassName="FGTanBlock";ve(q6.ClassName,q6);class J6 extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicAsin(t),J6.ClassName,e)}_polymorphicAsin(e){return Fa(e,Math.asin)}}J6.ClassName="FGAsinBlock";ve(J6.ClassName,J6);class eE extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicAcos(t),eE.ClassName,e)}_polymorphicAcos(e){return Fa(e,Math.acos)}}eE.ClassName="FGAcosBlock";ve(eE.ClassName,eE);class tE extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicAtan(t),tE.ClassName,e)}_polymorphicAtan(e){return Fa(e,Math.atan)}}tE.ClassName="FGAtanBlock";ve(tE.ClassName,tE);class iE extends Lo{constructor(e){super(Ot,Ot,Ot,(t,i)=>this._polymorphicAtan2(t,i),iE.ClassName,e)}_polymorphicAtan2(e,t){return mV(e,t,Math.atan2)}}iE.ClassName="FGAtan2Block";ve(iE.ClassName,iE);class rE extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicSinh(t),rE.ClassName,e)}_polymorphicSinh(e){return Fa(e,Math.sinh)}}rE.ClassName="FGSinhBlock";ve(rE.ClassName,rE);class sE extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicCosh(t),sE.ClassName,e)}_polymorphicCosh(e){return Fa(e,Math.cosh)}}sE.ClassName="FGCoshBlock";ve(sE.ClassName,sE);class nE extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicTanh(t),nE.ClassName,e)}_polymorphicTanh(e){return Fa(e,Math.tanh)}}nE.ClassName="FGTanhBlock";ve(nE.ClassName,nE);class aE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicAsinh(t),aE.ClassName,e)}_polymorphicAsinh(e){return Fa(e,Math.asinh)}}aE.ClassName="FGAsinhBlock";ve(aE.ClassName,aE);class oE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicAcosh(t),oE.ClassName,e)}_polymorphicAcosh(e){return Fa(e,Math.acosh)}}oE.ClassName="FGAcoshBlock";ve(oE.ClassName,oE);class lE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicAtanh(t),lE.ClassName,e)}_polymorphicAtanh(e){return Fa(e,Math.atanh)}}lE.ClassName="FGAtanhBlock";ve(lE.ClassName,lE);class cE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicExp(t),cE.ClassName,e)}_polymorphicExp(e){return Fa(e,Math.exp)}}cE.ClassName="FGExpBlock";ve(cE.ClassName,cE);class uE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicLog(t),uE.ClassName,e)}_polymorphicLog(e){return Fa(e,Math.log)}}uE.ClassName="FGLogBlock";ve(uE.ClassName,uE);class hE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicLog2(t),hE.ClassName,e)}_polymorphicLog2(e){return Fa(e,Math.log2)}}hE.ClassName="FGLog2Block";ve(hE.ClassName,hE);class dE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicLog10(t),dE.ClassName,e)}_polymorphicLog10(e){return Fa(e,Math.log10)}}dE.ClassName="FGLog10Block";ve(dE.ClassName,dE);class fE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicSqrt(t),fE.ClassName,e)}_polymorphicSqrt(e){return Fa(e,Math.sqrt)}}fE.ClassName="FGSqrtBlock";ve(fE.ClassName,fE);class pE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicCubeRoot(t),pE.ClassName,e)}_polymorphicCubeRoot(e){return Fa(e,Math.cbrt)}}pE.ClassName="FGCubeRootBlock";ve(pE.ClassName,pE);class mE extends Lo{constructor(e){super(Ot,Js,Js,(t,i)=>this._polymorphicPow(t,i),mE.ClassName,e)}_polymorphicPow(e,t){return mV(e,t,Math.pow)}}mE.ClassName="FGPowBlock";ve(mE.ClassName,mE);class gE extends Ns{constructor(e){super(Ot,Js,t=>this._polymorphicLength(t),gE.ClassName,e)}_polymorphicLength(e){switch(mc(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}gE.ClassName="FGLengthBlock";ve(gE.ClassName,gE);class _E extends Ns{constructor(e){super(Ot,Ot,t=>this._polymorphicNormalize(t),_E.ClassName,e)}_polymorphicNormalize(e){switch(mc(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}_E.ClassName="FGNormalizeBlock";ve(_E.ClassName,_E);class vE extends Lo{constructor(e){super(i_,i_,i_,(t,i)=>D.Cross(t,i),vE.ClassName,e)}}vE.ClassName="FGCrossBlock";ve(vE.ClassName,vE);class yE extends Lo{constructor(e){super(IZ,Js,IZ,(t,i)=>we.Transform(t,he.RotationZ(i)),yE.ClassName,e)}}yE.ClassName="FGRotate2DBlock";ve(yE.ClassName,yE);class xE extends e2e{constructor(e){super(i_,i_,Js,i_,(t,i,r)=>D.TransformCoordinates(t,he.RotationAxis(i,r)),xE.ClassName,e)}}xE.ClassName="FGRotate3DBlock";ve(xE.ClassName,xE);class AE extends Ns{constructor(e){super(wv,wv,t=>he.Transpose(t),AE.ClassName,e)}}AE.ClassName="FGTransposeBlock";ve(AE.ClassName,AE);class bE extends Ns{constructor(e){super(wv,Js,t=>t.determinant(),bE.ClassName,e)}}bE.ClassName="FGDeterminantBlock";ve(bE.ClassName,bE);class CE extends Ns{constructor(e){super(wv,wv,t=>he.Invert(t),CE.ClassName,e)}}CE.ClassName="FGInvertMatrixBlock";ve(CE.ClassName,CE);class SE extends Lo{constructor(e){super(wv,wv,wv,(t,i)=>i.multiply(t),SE.ClassName,e)}}SE.ClassName="FGMatMulBlock";ve(SE.ClassName,SE);class EE extends Ns{constructor(e){super(La,La,t=>new Ka(~t.value),EE.ClassName,e)}}EE.ClassName="FGBitwiseNotBlock";ve(EE.ClassName,EE);class TE extends Lo{constructor(e){super(La,La,La,(t,i)=>new Ka(t.value&i.value),TE.ClassName,e)}}TE.ClassName="FGBitwiseAndBlock";ve(TE.ClassName,TE);class ME extends Lo{constructor(e){super(La,La,La,(t,i)=>new Ka(t.value|i.value),ME.ClassName,e)}}ME.ClassName="FGBitwiseOrBlock";ve(ME.ClassName,ME);class RE extends Lo{constructor(e){super(La,La,La,(t,i)=>new Ka(t.value^i.value),RE.ClassName,e)}}RE.ClassName="FGBitwiseXorBlock";ve(RE.ClassName,RE);class IE extends Lo{constructor(e){super(La,La,La,(t,i)=>new Ka(t.value<new Ka(t.value>>i.value),PE.ClassName,e)}}PE.ClassName="FGBitwiseRightShiftBlock";ve(PE.ClassName,PE);class wE extends Ns{constructor(e){super(La,La,t=>new Ka(Math.clz32(t.value)),wE.ClassName,e)}}wE.ClassName="FGCountLeadingZerosBlock";ve(wE.ClassName,wE);class DE extends Ns{constructor(e){super(La,La,t=>new Ka(t.value?31-Math.clz32(t.value&-t.value):32),DE.ClassName,e)}}DE.ClassName="FGCountTrailingZerosBlock";ve(DE.ClassName,DE);function HPt(s){let e=0;for(;s;)e+=s&1,s>>=1;return e}class LE extends Ns{constructor(e){super(La,La,t=>new Ka(HPt(t.value)),LE.ClassName,e)}}LE.ClassName="FGCountOneBitsBlock";ve(LE.ClassName,LE);class _D extends dD{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const i=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return _D.ClassName}}_D.ClassName="FGSceneReadyEventBlock";ve("FGSceneReadyEventBlock",_D);class OE extends dD{constructor(e){super(e),this.config=e;for(let t=0;t{for(let r=0;r{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return NE.ClassName}}NE.ClassName="FGSceneTickEventBlock";ve(NE.ClassName,NE);const jPt=Object.freeze(Object.defineProperty({__proto__:null,AbstractActionManager:Jh,AbstractAssetTask:xg,AbstractEngine:Ge,AbstractMesh:Li,AbstractScene:Oa,AcquireNativeObjectAsync:kke,Action:an,ActionEvent:Hn,ActionManager:hs,AddBlock:cHe,get AddressMode(){return ahe},AdvancedTimer:yUe,AlignBlock:Fje,AlphaState:n9e,AmmoJSPlugin:jm,AnaglyphArcRotateCamera:q9e,AnaglyphFreeCamera:J9e,AnaglyphGamepadCamera:eBe,AnaglyphPostProcess:Lge,AnaglyphUniversalCamera:tBe,Analyser:h2t,AndOrNotEvaluator:wy,Angle:zm,Animatable:yge,get AnimatedInputBlockTypes(){return w1},Animation:tt,AnimationAssetTask:tPt,AnimationEvent:MJ,AnimationGroup:Lm,AnimationGroupMask:J_t,get AnimationGroupMaskMode(){return Iue},get AnimationKeyInterpolation(){return Rue},AnimationPropertiesOverride:K_t,AnimationRange:$S,AnisotropyBlock:qz,ApplyLut:NKe,ApplyPostProcess:aee,Arc2:y9e,ArcFollowCamera:wge,ArcRotateCamera:Kr,ArcRotateCameraGamepadInput:Az,ArcRotateCameraInputsManager:kJ,ArcRotateCameraKeyboardMoveInput:P0,ArcRotateCameraMouseWheelInput:Jw,ArcRotateCameraPointersInput:Th,ArcRotateCameraVRDeviceOrientationInput:Mge,ArcTan2Block:IHe,AssetContainer:_z,get AssetTaskState(){return Wde},AssetsManager:iPt,AssetsProgressEvent:kJe,AsyncLock:_Pt,AsyncLoop:Of,AttachToBoxBehavior:p2t,AudioEngine:O9e,AudioSceneComponent:xh,get AutoLayoutMode(){return _he},AutoReleaseWorkerPool:rD,AutoRotationBehavior:z9e,AxesViewer:hv,Axis:Da,AxisDragGizmo:Bf,AxisScaleGizmo:kf,BRDFTextureTools:Y4t,BabylonFileLoaderConfiguration:XB,BackEase:A9e,BackgroundMaterial:xr,BakedVertexAnimationManager:sT,BallAndSocketConstraint:r8t,BaseCameraMouseWheelInput:yz,BaseCameraPointersInput:BJ,BaseError:ZS,BaseParticleSystem:zo,BaseSixDofDragBehavior:I1,BaseTexture:$r,BasisFileInfo:PEt,BasisTools:Eee,BasisToolsOptions:zv,BasisTranscodeConfiguration:wEt,BezierCurve:v9e,BezierCurveEase:Z_t,BiPlanarBlock:YHe,BinaryFileAssetTask:GJe,BindBonesParameters:ql,BindFogParameters:ml,BindLight:fz,BindLightProperties:P9e,BindLights:hu,BindLogDepth:uo,BindMorphTargetParameters:I0,BindSceneUniformBuffer:$w,BindTextureMatrix:sn,BlackAndWhitePostProcess:sV,get BlendFactor(){return bhe},get BlendOperation(){return Che},BloomEffect:Fde,BloomMergePostProcess:Gee,BlurPostProcess:Ho,Bone:js,BoneAxesViewer:Ovt,BoneIKController:Dd,BoneLookController:Gl,BonesBlock:KKe,BooleanGeometryBlock:Nee,get BooleanGeometryOperations(){return Gm},BounceEase:H_t,BouncingBehavior:tx,BoundingBlock:Xje,BoundingBox:ed,BoundingBoxGizmo:S1e,BoundingBoxRenderer:qZe,BoundingInfo:Oc,BoundingInfoHelper:Svt,BoundingSphere:qm,BoxBlock:Iee,BoxBuilder:Nvt,BoxParticleEmitter:Sv,Buffer:Mo,get BufferBindingType(){return hhe},get BufferMapState(){return Jue},get BufferUsage(){return Ds},CSG:Om,Camera:Nt,CameraGizmo:lP,CameraInputTypes:pc,CameraInputsManager:xz,CannonJSPlugin:xZ,get CanvasAlphaMode(){return Lhe},CapsuleBlock:__e,CapsuleBuilder:zvt,CascadedShadowGenerator:Cl,ChromaticAberrationPostProcess:vg,CircleEase:x9e,CircleOfConfusionPostProcess:fT,ClampBlock:Mee,ClearCoatBlock:l6,ClipPlanesBlock:nHe,ClipboardEventTypes:Zf,ClipboardInfo:YQ,CloudBlock:n_e,CloudPoint:dYe,Collider:Lz,Color3:Re,Color3Gradient:tYe,Color4:Ze,ColorCorrectionPostProcess:nV,ColorCurves:Ln,ColorGradient:F_e,ColorGradingTexture:sx,ColorMergerBlock:mHe,ColorSplitterBlock:k1e,get ColorWrite(){return Ahe},CombineAction:FFe,get CompareFunction(){return che},CompatibilityOptions:t2t,get CompilationMessageType(){return mhe},CompleteGreasedLineColorTable:Cje,CompleteGreasedLineWidthTable:bje,get CompressionCodes(){return E1},get ComputeBindingType(){return Yue},ComputeEffect:i6,ComputeNormalsBlock:Ije,get ComputePassTimestampLocation(){return Rhe},ComputeShader:Hm,ComputeShaderBoundingHelper:_ke,ComputeShaderParticleSystem:eYe,Condition:JP,ConditionBlock:S_e,get ConditionBlockTests(){return nl},ConditionalBlock:HHe,get ConditionalBlockConditions(){return Pd},ConeDirectedParticleEmitter:Jz,ConeParticleEmitter:oD,Constants:Le,ContainerAssetTask:UJe,get ConversionMode(){return Gde},ConvolutionPostProcess:yg,get Coordinate(){return wue},CopyFloatData:M9e,CopyTextureToTexture:aqe,CopyTools:d2t,CreateBox:ph,CreateBoxVertexData:$J,CreateCapsule:Oz,CreateCapsuleVertexData:qJ,CreateCylinder:ou,CreateCylinderVertexData:QJ,CreateDashedLines:tee,CreateDashedLinesVertexData:a1e,CreateDecal:nee,CreateDecoderAsync:zKe,CreateDisc:iD,CreateDiscVertexData:JJ,CreateEnvTextureAsync:Oke,CreateGeodesic:Ake,CreateGoldberg:Cke,CreateGoldbergVertexData:bke,CreateGreasedLine:_Mt,CreateGreasedLineMaterial:xje,CreateGround:aT,CreateGroundFromHeightMap:jJ,CreateGroundFromHeightMapVertexData:Qge,CreateGroundVertexData:P1,CreateHemisphere:Gk,CreateIcoSphere:Uz,CreateIcoSphereVertexData:see,CreateImageBitmapFromSource:kge,CreateImageDataArrayBufferViews:cee,CreateLathe:iee,CreateLineSystem:IS,CreateLineSystemVertexData:n1e,CreateLines:dn,CreatePlane:b_,CreatePlaneVertexData:vz,CreatePolygon:Nz,CreatePolygonVertexData:o1e,CreatePolyhedron:n6,CreatePolyhedronVertexData:l1e,CreateResizedCopy:wke,CreateRibbon:c_,CreateRibbonVertexData:Jge,CreateScreenshot:cV,CreateScreenshotAsync:Q_e,CreateScreenshotUsingRenderTarget:uV,CreateScreenshotUsingRenderTargetAsync:$_e,CreateScreenshotWithResizeAsync:$Je,CreateSegmentedBoxVertexData:vke,CreateSphere:kc,CreateSphereVertexData:ZJ,CreateText:Ske,CreateTextShapePaths:u1e,CreateTiledBox:i1e,CreateTiledBoxVertexData:t1e,CreateTiledGround:HJ,CreateTiledGroundVertexData:Yge,CreateTiledPlane:e1e,CreateTiledPlaneVertexData:aP,CreateTorus:ug,CreateTorusKnot:eee,CreateTorusKnotVertexData:r1e,CreateTorusVertexData:XJ,CreateTube:ree,CrossBlock:hHe,CubeMapToSphericalPolynomialTools:oT,CubeTexture:_a,CubeTextureAssetTask:HJe,CubicEase:j_t,get CullMode(){return xhe},CurrentScreenBlock:O1e,Curve3:Jp,CurveBlock:ZHe,get CurveBlockTypes(){return Tn},CustomBlock:dHe,CustomOptimization:YJe,CustomParticleEmitter:Ev,CustomProceduralTexture:WKe,CylinderBlock:g_e,CylinderBuilder:Lvt,CylinderDirectedParticleEmitter:eV,CylinderParticleEmitter:lD,DDSTools:Ks,DataBuffer:Zm,DataReader:yB,DataStorage:Yde,Database:Ru,DebugBlock:Gje,DebugLayer:s6,get DebugLayerTab(){return Xue},DecalBuilder:o3t,DecalMapConfiguration:aD,DecalMapDefines:qHe,Decode:age,DecodeBase64ToBinary:lz,DecodeBase64ToString:AJ,DecodeBase64UrlToBinary:Yw,DecodeBase64UrlToString:gge,DecodeFloat32:TKe,DecodeRunLength:FKe,DeepCopier:Nl,DefaultCollisionCoordinator:bBe,DefaultKTX2DecoderOptions:rUe,DefaultLoadingScreen:fv,DefaultRenderingPipeline:Fl,Deferred:uS,DepthCullingState:hge,DepthOfFieldBlurPostProcess:$k,DepthOfFieldEffect:kde,get DepthOfFieldEffectBlurLevel(){return Bde},DepthOfFieldMergePostProcess:IYe,DepthPeelingRenderer:j1,DepthPeelingSceneComponent:eqe,DepthReducer:pVe,DepthRenderer:u_,DepthRendererSceneComponent:JZe,DepthSortedParticle:uYe,DerivativeBlock:QKe,DesaturateBlock:GHe,DetailMapConfiguration:C_,get DeviceInputEventType(){return Sue},get DeviceLostReason(){return Ohe},DeviceOrientationCamera:UJ,DeviceSource:Eue,DeviceSourceManager:_9e,get DeviceType(){return ui},DirectionalLight:dc,DirectionalLightFrustumViewer:h3t,DiscBlock:v_e,DiscBuilder:Gvt,DiscardBlock:XKe,DisplayPassPostProcess:Wee,DistanceBlock:SHe,DistanceConstraint:s8t,DistanceJoint:Bvt,DivideBlock:vHe,DoNothingAction:Zme,DomManagement:r_t,DotBlock:fHe,DracoCompression:Kl,DrawWrapper:Ro,get DualSenseInput(){return Aue},get DualShockButton(){return Uue},get DualShockDpad(){return zue},get DualShockInput(){return xue},DualShockPad:j9e,DumpTools:O2t,DynamicFloat32Array:j2,DynamicTexture:Qf,get EXROutputType(){return D1},EasingFunction:ya,EdgesRenderer:oV,Effect:zi,EffectFallbacks:oa,EffectLayer:Ah,EffectLayerSceneComponent:bUe,EffectRenderer:Pz,EffectWrapper:J1,ElasticEase:X_t,ElbowBlock:XHe,EncodeArrayBufferToBase64:oz,EndsWith:jFe,Engine:vt,EngineFactory:G4t,get EngineFormat(){return Uhe},EngineInstrumentation:xUe,EngineStore:Rt,EngineView:d3t,EnvironmentHelper:Sx,EnvironmentTextureTools:O3t,Epsilon:ci,EquiRectangularCubeTexture:ow,EquiRectangularCubeTextureAssetTask:XJe,ErrorCodes:x_,get ErrorFilter(){return Nhe},EventConstants:iT,EventState:$me,ExecuteCodeAction:BFe,ExitFullscreen:Vge,ExitPointerlock:Gge,ExponentialEase:b9e,ExrLoaderGlobalConfiguration:wS,ExternalTexture:g1e,ExtractHighlightsPostProcess:Vee,ExtrudePolygon:Fz,ExtrudeShape:Bz,ExtrudeShapeCustom:kz,FactorGradient:B_e,FadeInOutBehavior:m2t,get FeatureName(){return que},get FileTools(){return y5},FileToolsOptions:Ia,FilesInput:H_e,FilesInputStore:RS,get FilterMode(){return ohe},FilterPostProcess:aV,FlowGraph:d6,FlowGraphAbsBlock:P6,FlowGraphAcosBlock:eE,FlowGraphAcoshBlock:oE,FlowGraphAddBlock:x6,FlowGraphAsinBlock:J6,FlowGraphAsinhBlock:aE,FlowGraphAtan2Block:iE,FlowGraphAtanBlock:tE,FlowGraphAtanhBlock:lE,FlowGraphBitwiseAndBlock:TE,FlowGraphBitwiseLeftShiftBlock:IE,FlowGraphBitwiseNotBlock:EE,FlowGraphBitwiseOrBlock:ME,FlowGraphBitwiseRightShiftBlock:PE,FlowGraphBitwiseXorBlock:RE,FlowGraphBlock:o3,FlowGraphBranchBlock:Oet,FlowGraphCeilBlock:O6,FlowGraphClampBlock:z6,FlowGraphConditionalDataBlock:Het,FlowGraphConnection:RZ,get FlowGraphConnectionType(){return Zde},FlowGraphConsoleLogBlock:f6,FlowGraphConstantBlock:Xet,FlowGraphContext:DZ,FlowGraphContextLogger:GPt,FlowGraphCoordinateTransformBlock:jet,FlowGraphCoordinator:OS,FlowGraphCosBlock:Z6,FlowGraphCoshBlock:sE,FlowGraphCountLeadingZerosBlock:wE,FlowGraphCountOneBitsBlock:LE,FlowGraphCountTrailingZerosBlock:DE,FlowGraphCounterBlock:zet,FlowGraphCrossBlock:vE,FlowGraphCubeRootBlock:pE,FlowGraphDataConnection:PZ,FlowGraphDebounceBlock:Vet,FlowGraphDegToRadBlock:Y6,FlowGraphDeterminantBlock:bE,FlowGraphDivideBlock:C6,FlowGraphDoNBlock:m6,FlowGraphDotBlock:E6,FlowGraphEBlock:T6,FlowGraphEqBlock:W6,FlowGraphEventBlock:dD,FlowGraphExecutionBlock:rg,FlowGraphExpBlock:cE,FlowGraphFlipFlopBlock:Get,FlowGraphFloorBlock:L6,FlowGraphForLoopBlock:Net,FlowGraphFractBlock:N6,FlowGraphGetPropertyBlock:y6,FlowGraphGetVariableBlock:v6,FlowGraphGreaterThanBlock:H6,FlowGraphGreaterThanOrEqualBlock:j6,FlowGraphInfBlock:R6,FlowGraphInterpolateBlock:G6,FlowGraphInvertMatrixBlock:CE,FlowGraphIsInfBlock:_V,FlowGraphIsNanBlock:X6,FlowGraphLengthBlock:gE,FlowGraphLessThanBlock:K6,FlowGraphLessThanOrEqualBlock:gV,FlowGraphLog10Block:dE,FlowGraphLog2Block:hE,FlowGraphLogBlock:uE,FlowGraphLogicAndBlock:Zet,FlowGraphLogicNotBlock:Jet,FlowGraphLogicOrBlock:qet,FlowGraphMatMulBlock:SE,FlowGraphMaxBlock:U6,FlowGraphMeshPickEventBlock:h6,FlowGraphMinBlock:k6,FlowGraphMultiGateBlock:Bet,FlowGraphMultiplyBlock:b6,FlowGraphNaNBlock:I6,FlowGraphNegBlock:F6,FlowGraphNormalizeBlock:_E,FlowGraphPauseAnimationBlock:Ket,FlowGraphPiBlock:M6,FlowGraphPlayAnimationBlock:_w,FlowGraphPowBlock:mE,FlowGraphRadToDegBlock:Q6,FlowGraphRandomBlock:S6,FlowGraphReceiveCustomEventBlock:OE,FlowGraphRemainderBlock:B6,FlowGraphRotate2DBlock:yE,FlowGraphRotate3DBlock:xE,FlowGraphSaturateBlock:V6,FlowGraphSceneReadyEventBlock:_D,FlowGraphSceneTickEventBlock:NE,FlowGraphSendCustomEventBlock:pD,FlowGraphSequenceBlock:_6,FlowGraphSetPropertyBlock:fD,FlowGraphSetVariableBlock:p6,FlowGraphSignBlock:w6,FlowGraphSignalConnection:wZ,FlowGraphSinBlock:$6,FlowGraphSinhBlock:rE,FlowGraphSqrtBlock:fE,get FlowGraphState(){return qde},FlowGraphStopAnimationBlock:Wet,FlowGraphSubtractBlock:A6,FlowGraphSwitchBlock:ket,FlowGraphTanBlock:q6,FlowGraphTanhBlock:nE,FlowGraphThrottleBlock:Fet,FlowGraphTimerBlock:mD,FlowGraphTransposeBlock:AE,FlowGraphTruncBlock:D6,FlowGraphWaitAllBlock:Uet,FlowGraphWhileLoopBlock:g6,FluidRenderer:Hee,FluidRendererSceneComponent:oqe,get FluidRenderingDebug(){return zde},FluidRenderingObject:K_e,FluidRenderingObjectCustomParticles:nqe,FluidRenderingObjectParticleSystem:sqe,FluidRenderingTargetRenderer:Vde,FlyCamera:eD,FlyCameraInputsManager:W9e,FlyCameraKeyboardInput:i3,FlyCameraMouseInput:bz,FogBlock:rHe,FollowBehavior:y2t,FollowCamera:au,FollowCameraInputsManager:K9e,FollowCameraKeyboardMoveInput:Jl,FollowCameraMouseWheelInput:zx,FollowCameraPointersInput:Mh,FragCoordBlock:$Ke,FragDepthBlock:eHe,FragmentOutputBlock:dv,FramingBehavior:hh,FreeCamera:Dl,FreeCameraDeviceOrientationInput:Rge,FreeCameraGamepadInput:Tz,FreeCameraInputsManager:Ez,FreeCameraKeyboardMoveInput:ef,FreeCameraMouseInput:Cz,FreeCameraMouseWheelInput:w0,FreeCameraTouchInput:Sz,FreeCameraVirtualJoystickInput:Ige,FresnelBlock:AHe,FresnelParameters:Wk,FromHalfFloat:Im,get FrontFace(){return yhe},FrontFacingBlock:YKe,Frustum:Od,FxaaPostProcess:pT,GIRSM:c5t,GIRSMManager:jee,GIRSMRenderPluginMaterial:Kf,GPUParticleSystem:Hd,GPUPicker:H2t,GUID:N_t,Gamepad:hl,GamepadCamera:zJ,GamepadManager:X9e,GamepadSystemSceneComponent:Y9e,GaussianSplattingMaterial:uw,GaussianSplattingMesh:Cv,GenerateBase64StringFromPixelData:FJ,GenerateBase64StringFromTexture:Ege,GenerateBase64StringFromTextureAsync:Tge,GenericPad:G9e,GeodesicData:zz,Geometry:So,GeometryArcTan2Block:Yje,GeometryBufferRenderer:Nr,GeometryBufferRendererSceneComponent:BYe,GeometryClampBlock:Fee,GeometryCollectionBlock:M_e,GeometryCrossBlock:tXe,GeometryCurveBlock:N_e,get GeometryCurveBlockTypes(){return gr},GeometryDesaturateBlock:iXe,GeometryDistanceBlock:nXe,GeometryDotBlock:aXe,GeometryElbowBlock:Rje,GeometryInfoBlock:Wje,GeometryInputBlock:lo,GeometryLengthBlock:oXe,GeometryLerpBlock:Qje,GeometryModBlock:Jje,GeometryNLerpBlock:$je,GeometryOptimizeBlock:Pee,GeometryOutputBlock:c_e,GeometryPosterizeBlock:rXe,GeometryPowBlock:eXe,GeometryReplaceColorBlock:sXe,GeometryRotate2dBlock:lXe,GeometrySmoothStepBlock:qje,GeometryStepBlock:Zje,GeometryTextureBlock:L_e,GeometryTextureFetchBlock:O_e,GeometryTransformBlock:P_e,GeometryTrigonometryBlock:I_e,get GeometryTrigonometryBlockOperations(){return Xr},GetClass:Xn,GetClassName:Q1t,GetDOMTextContent:az,GetEnvInfo:lee,GetEnvironmentBRDFTexture:Hz,GetExrHeader:RKe,GetFogState:wJ,GetFontOffset:Bge,GetInternalFormatFromBasisFormat:yKe,GetPointsCount:Aje,GetTGAHeader:Yz,GetTextureDataAsync:Dke,Gizmo:jn,get GizmoAnchorPoint(){return Hue},get GizmoCoordinatesMode(){return jue},GizmoManager:W4t,GlowLayer:ao,GoldbergMesh:Vz,GradientBlock:NHe,GradientBlockColorStep:QQ,GradientHelper:Kh,GrainPostProcess:mT,GreasedLineBaseMesh:l_e,GreasedLineMaterialDefaults:Rl,GreasedLineMesh:bl,get GreasedLineMeshColorDistribution(){return gde},get GreasedLineMeshColorDistributionType(){return cde},get GreasedLineMeshColorMode(){return lde},get GreasedLineMeshMaterialType(){return ode},get GreasedLineMeshWidthDistribution(){return _de},GreasedLinePluginMaterial:f_,get GreasedLineRibbonAutoDirectionMode(){return mde},get GreasedLineRibbonFacesMode(){return pde},GreasedLineRibbonMesh:Ra,get GreasedLineRibbonPointsMode(){return fde},GreasedLineSimpleMaterial:o_e,GreasedLineTools:Cs,GridBlock:p_e,GroundBuilder:V2t,GroundMesh:tD,HDRCubeTexture:e_,HDRCubeTextureAssetTask:jJe,HDRFiltering:K1e,HDRTools:Wxt,Halton2DSequence:fje,HandConstraintBehavior:x2t,get HandConstraintOrientation(){return Oue},get HandConstraintVisibility(){return Nue},get HandConstraintZone(){return Lue},get HandPart(){return Hhe},HandleFallbacksForShadows:Zo,HardwareScalingOptimization:Kde,HavokPlugin:f8t,HeightToNormalBlock:$z,HemisphereBuilder:K4t,HemisphericLight:$f,HemisphericParticleEmitter:tV,HighlightLayer:Lc,HighlightsPostProcess:y8t,Hinge2Joint:Uvt,HingeConstraint:n8t,HingeJoint:kvt,HtmlElementTexture:See,HufUncompress:LKe,IWebXRControllerPhysicsOptions:SPt,IcoSphereBlock:d_e,IcoSphereBuilder:e3t,ImageAssetTask:WJe,ImageProcessingBlock:t_e,ImageProcessingConfiguration:lr,ImageProcessingPostProcess:Kee,ImageSourceBlock:y0,IncrementValueAction:LFe,get IndexFormat(){return Ehe},InputBlock:nr,get InspectableType(){return Xde},InstancedLinesMesh:s1e,InstancedMesh:C0,InstancesBlock:HKe,InstantiateBlock:kje,InstantiateLinearBlock:Uje,InstantiateOnFacesBlock:w_e,InstantiateOnVerticesBlock:Dee,InstantiateOnVolumeBlock:Lee,InstantiateRadialBlock:zje,InstantiatedEntries:L9e,IntFloatConverterBlock:Vje,InterleaveScalar:Z1e,InternalTexture:zr,get InternalTextureSource(){return mue},InterpolateValueAction:WFe,IntersectionInfo:lZ,IsBase64DataUrl:uz,IsDocumentAvailable:MS,IsFileURL:mge,IsNavigatorAvailable:Ny,IsWindowObjectExist:To,IsWrapper:TJ,get JoystickAxis(){return Fue},KeepAssets:D9e,KeyboardEventTypes:lg,KeyboardInfo:oZ,KeyboardInfoPre:vue,KhronosTextureContainer:wu,KhronosTextureContainer2:Zs,LatheBuilder:Zvt,Layer:yee,LayerSceneComponent:CUe,LengthBlock:EHe,LensFlare:xee,LensFlareSystem:bv,LensFlareSystemSceneComponent:Hze,LensFlaresOptimization:t$,LensRenderingPipeline:B8t,LerpBlock:_He,Light:Zi,LightBlock:TZ,LightGizmo:$p,LightInformationBlock:jKe,LineEdgesRenderer:tqe,LinesBuilder:jvt,LinesMesh:Jm,LoadFile:Uv,LoadFileError:tw,LoadImage:Xw,LoadImageConfiguration:gue,get LoadOp(){return Phe},LoadTextureFromTranscodeResult:CZ,LockConstraint:o8t,Logger:fe,get MapMode(){return ehe},MapRangeBlock:Tje,MappingBlock:D_e,get MappingTypes(){return Vm},Material:Ye,MaterialAnisotropicDefines:Zke,MaterialClearCoatDefines:Qke,MaterialDefines:_s,MaterialDetailMapDefines:gBe,MaterialFlags:Je,MaterialGreasedLineDefines:JHe,MaterialHelper:wn,MaterialIridescenceDefines:$ke,MaterialPluginBase:fu,get MaterialPluginEvent(){return ade},MaterialPluginManager:cv,MaterialSheenDefines:qke,MaterialSubSurfaceDefines:Jke,MathBlock:C_e,get MathBlockOperations(){return Pu},Matrix:he,MatrixBuilderBlock:KHe,MatrixComposeBlock:Kje,MatrixDeterminantBlock:QHe,MatrixTransposeBlock:$He,MaxBlock:bHe,MergeGeometryBlock:T_e,MergeMeshesOptimization:Mv,Mesh:Ee,MeshAssetTask:zJe,MeshAttributeExistsBlock:a_e,get MeshAttributeExistsBlockTypes(){return nde},MeshBlock:h_e,MeshBuilder:Xh,get MeshDebugMode(){return ude},MeshDebugPluginMaterial:dl,MeshExploder:rPt,MeshLODLevel:w9e,MeshParticleEmitter:Bee,MeshUVSpaceRenderer:y1,MeshoptCompression:N1,MinBlock:CHe,MinMaxReducer:fVe,get MipmapFilterMode(){return lhe},MirrorTexture:Av,ModBlock:WHe,ModelShape:Cde,MorphTarget:rx,MorphTargetManager:f0,MorphTargetsBlock:e_e,MotionBlurPostProcess:Hx,MotorEnabledJoint:qge,MultiMaterial:Zd,MultiObserver:j_e,MultiPointerScaleBehavior:_2t,MultiRenderTarget:nv,MultiplyBlock:yZ,NLerpBlock:FHe,NativeDataStream:Cx,NativeEngine:a6,get NativePointerInput(){return yue},NativeXRFrame:Eet,NativeXRLayerRenderTargetTextureProvider:xBe,NativeXRLayerWrapper:yBe,NativeXRRenderTarget:ABe,NegateBlock:THe,Node:ns,NodeGeometry:Qh,NodeGeometryBlock:Ri,get NodeGeometryBlockConnectionPointTypes(){return me},NodeGeometryBuildState:Sje,NodeGeometryConnectionPoint:xde,get NodeGeometryConnectionPointCompatibilityStates(){return vde},get NodeGeometryConnectionPointDirection(){return yde},get NodeGeometryContextualSources(){return os},NodeMaterial:Ss,NodeMaterialBlock:qt,get NodeMaterialBlockConnectionPointMode(){return rde},get NodeMaterialBlockConnectionPointTypes(){return ee},get NodeMaterialBlockTargets(){return be},NodeMaterialConnectionPoint:o6,get NodeMaterialConnectionPointCompatibilityStates(){return Vhe},NodeMaterialConnectionPointCustomObject:ra,get NodeMaterialConnectionPointDirection(){return Ghe},NodeMaterialDefines:_B,get NodeMaterialModes(){return Eu},NodeMaterialOptimizer:pTt,get NodeMaterialSystemValues(){return mr},NodeMaterialTeleportInBlock:oHe,NodeMaterialTeleportOutBlock:lHe,NoiseBlock:Mje,NoiseProceduralTexture:Hk,NormalBlendBlock:kHe,NormalizeBlock:pHe,NormalizeVectorBlock:wje,NullBlock:Eje,NullEngine:Tke,NullEngineOptions:Eke,Observable:Ae,Observer:EFe,OcclusionMaterial:hbt,Octree:r6,OctreeBlock:Uk,OctreeSceneComponent:Zge,OimoJSPlugin:Yhe,OnAfterEnteringVRObservableEvent:W2t,OneMinusBlock:i_e,get Orientation(){return Mue},OutlineRenderer:pw,PBRAnisotropicConfiguration:Wx,PBRBaseMaterial:Pr,PBRBaseSimpleMaterial:Gu,PBRClearCoatConfiguration:Xo,PBRIridescenceConfiguration:Uc,PBRMaterial:Lt,PBRMaterialDefines:Bhe,PBRMetallicRoughnessBlock:Qo,PBRMetallicRoughnessMaterial:h_,PBRSheenConfiguration:L0,PBRSpecularGlossinessMaterial:d_,PBRSubSurfaceConfiguration:Fn,PHI:Co,PadNumber:YFe,PanoramaToCubeMapTools:r3,ParseFloat16:EKe,ParseFloat32:Iu,ParseInt32:Ym,ParseInt64:SKe,ParseNullTerminatedString:EZ,ParseUint16:Kk,ParseUint32:t_,ParseUint8:Qz,ParseUint8Array:Q1e,ParseValue:MKe,Particle:dw,ParticleBlendMultiplyBlock:B1e,ParticleHelper:c6,ParticleRampGradientBlock:F1e,ParticleSystem:bs,ParticleSystemSet:Vv,ParticleTextureBlock:N1e,ParticlesOptimization:i$,PassCubePostProcess:Dge,PassPostProcess:D0,Path2:Qw,Path3D:qS,PathCursor:q_t,PerfCollectionStrategy:dPt,PerfCounter:io,PerformanceConfigurator:al,PerformanceMonitor:Oge,PerformanceViewerCollector:jp,PerturbNormalBlock:nD,PhotoDome:sw,Physics6DoFConstraint:MYe,Physics6DoFLimit:i8t,get PhysicsActivationControl(){return Dde},PhysicsAggregate:RYe,PhysicsBody:Uee,PhysicsConstraint:s3,get PhysicsConstraintAxis(){return Tde},get PhysicsConstraintAxisLimitMode(){return Ede},get PhysicsConstraintMotorType(){return Ide},get PhysicsConstraintType(){return Mde},PhysicsEngine:j1e,PhysicsEngineV2:kee,get PhysicsEventType(){return Pde},PhysicsHelper:m8t,PhysicsImpostor:oi,PhysicsJoint:ks,get PhysicsMaterialCombineMode(){return Lde},get PhysicsMotionType(){return wde},get PhysicsPrestepType(){return H1},PhysicsRadialExplosionEventOptions:fP,get PhysicsRadialImpulseFalloff(){return Ode},PhysicsRaycastResult:Xz,PhysicsShape:N0,PhysicsShapeBox:V_e,PhysicsShapeCapsule:U_e,PhysicsShapeContainer:JMt,PhysicsShapeConvexHull:ZMt,PhysicsShapeCylinder:z_e,PhysicsShapeGroundMesh:t8t,PhysicsShapeHeightField:e8t,PhysicsShapeMesh:qMt,PhysicsShapeSphere:k_e,get PhysicsShapeType(){return Rde},PhysicsUpdraftEventOptions:G_e,get PhysicsUpdraftMode(){return Nde},PhysicsViewer:u3t,PhysicsVortexEventOptions:W_e,PickingInfo:Ko,get PipelineErrorReason(){return ghe},PivotTools:ds,Plane:Xl,PlaneBlock:u_e,PlaneBuilder:g2t,PlaneDragGizmo:oP,PlaneRotationGizmo:d0,PlayAnimationAction:OFe,PlaySoundAction:kFe,get PointColor(){return Sde},PointLight:ig,PointParticleEmitter:iV,PointerDragBehavior:sl,PointerEventTypes:yt,PointerInfo:Df,PointerInfoBase:vge,PointerInfoPre:g9e,get PointerInput(){return Ii},PointsCloudSystem:YMt,PointsGroup:ZQ,Polar:lMt,Polygon:Yvt,PolygonBuilder:Qvt,PolygonMeshBuilder:yke,PolyhedronBuilder:Jvt,PolyhedronData:fZ,PositionGizmo:fee,PositionNormalTextureVertex:f1e,PositionNormalVertex:d1e,PostProcess:Ft,PostProcessManager:Bk,PostProcessRenderEffect:Yr,PostProcessRenderPipeline:n3,PostProcessRenderPipelineManager:VYe,PostProcessRenderPipelineManagerSceneComponent:GYe,PostProcessesOptimization:e$,PosterizeBlock:LHe,PowBlock:MHe,PowerEase:Y_t,get PowerPreference(){return Zue},PrePassOutputBlock:iHe,PrePassRenderer:oc,PrePassRendererSceneComponent:iqe,PrePassTextureBlock:aHe,PrecisionDate:Or,PredicateCondition:RFe,Predictor:$1e,PrepareAttributesForBakedVertexAnimation:Zw,PrepareAttributesForBones:Vu,PrepareAttributesForInstances:Ya,PrepareAttributesForMorphTargets:dz,PrepareAttributesForMorphTargetsInfluencers:rT,PrepareDefinesForAttributes:Na,PrepareDefinesForBakedVertexAnimation:Cge,PrepareDefinesForBones:DJ,PrepareDefinesForCamera:NJ,PrepareDefinesForFrameBoundValues:Hc,PrepareDefinesForLight:pz,PrepareDefinesForLights:du,PrepareDefinesForMergedUV:rn,PrepareDefinesForMisc:Kc,PrepareDefinesForMorphTargets:LJ,PrepareDefinesForMultiview:qw,PrepareDefinesForOIT:OJ,PrepareDefinesForPrePass:mz,PrepareUniformsAndSamplersForLight:gz,PrepareUniformsAndSamplersList:po,PressureObserverWrapper:Xee,get PrimitiveTopology(){return vhe},PrismaticConstraint:l8t,ProceduralTexture:O0,ProceduralTextureSceneComponent:gUe,get PropertyTypeForEdition(){return Whe},ProximityCastResult:_8t,PushAttributesForInstances:A_,PushMaterial:aa,QuadraticEase:xge,QuadraticErrorSimplification:vje,QuarticEase:Q_t,Quaternion:Pe,get QueryType(){return Dhe},QueueNewFrame:pge,QuinticEase:$_t,RGBDTextureTools:zk,RSMCreatePluginMaterial:Xx,Ragdoll:h8t,RagdollBoneProperties:u8t,RandomBlock:E_e,get RandomBlockLocks(){return Nd},RandomGUID:gh,RandomNumberBlock:RHe,RawCubeTexture:Tee,RawTexture:yn,RawTexture2DArray:Aee,RawTexture3D:cTt,Ray:$i,RayHelper:h1e,ReadFile:iw,ReadFileError:CJ,RecastJSCrowd:ZXe,RecastJSPlugin:DMt,ReciprocalBlock:wHe,ReflectBlock:zHe,ReflectionBlock:dT,ReflectionProbe:cT,ReflectionTextureBaseBlock:lw,ReflectionTextureBlock:sHe,ReflectiveShadowMap:o5t,Reflector:Jk,RefractBlock:VHe,RefractionBlock:Kx,RefractionPostProcess:jx,RefractionTexture:J1e,RegisterClass:ve,RegisterMaterialPlugin:k2t,RegisterNativeTypeAsync:Uke,RemapBlock:jz,get RenderPassTimestampLocation(){return Ihe},RenderTargetTexture:Rs,RenderTargetWrapper:Mz,RenderTargetsOptimization:Hde,RenderingGroup:Qp,RenderingGroupInfo:m9e,RenderingManager:Wl,ReplaceColorBlock:DHe,RequestFile:EJ,RequestFileError:Nk,RequestFullscreen:zge,RequestPointerlock:VJ,ResizeImageBitmap:Uge,RetryStrategy:HFe,ReverseLutFromBitmap:PKe,RibbonBuilder:Vvt,RichType:Rh,RichTypeAny:Ot,RichTypeBoolean:Ll,RichTypeColor3:Ret,RichTypeColor4:Iet,RichTypeFlowGraphInteger:La,RichTypeMatrix:wv,RichTypeNumber:Js,RichTypeQuaternion:Pet,RichTypeString:Tet,RichTypeVector2:IZ,RichTypeVector3:i_,RichTypeVector4:Met,RollingAverage:lBe,Rotate2dBlock:UHe,RotationGizmo:E1e,RotationXBlock:Dje,RotationYBlock:Lje,RotationZBlock:Oje,RuntimeAnimation:KFe,RuntimeError:R0,SSAO2RenderingPipeline:Yo,SSAORenderingPipeline:uD,SSRRenderingPipeline:on,get SamplerBindingType(){return dhe},Scalar:At,ScaleBlock:uHe,ScaleGizmo:T1e,ScalingBlock:Nje,ScanData:VKe,Scene:gt,SceneComponentConstants:ot,SceneDepthBlock:Zz,SceneInstrumentation:AUe,SceneLoader:Ys,get SceneLoaderAnimationGroupLoadingMode(){return zhe},SceneLoaderFlags:Eo,SceneOptimization:S_,SceneOptimizer:X_e,SceneOptimizerOptions:LS,get ScenePerformancePriority(){return Tue},SceneRecorder:oPt,SceneSerializer:X1,ScreenSizeBlock:ZKe,ScreenSpaceBlock:qKe,ScreenSpaceCurvaturePostProcess:hD,ScreenSpaceReflectionPostProcess:op,ScreenshotTools:nPt,SerializationHelper:qe,SetBasisTranscoderWorker:NEt,SetColorsBlock:A_e,SetCorsBehavior:SJ,SetMaterialIDBlock:R_e,SetNormalsBlock:x_e,SetParentAction:qme,SetPositionsBlock:y_e,SetStateAction:wFe,SetTangentsBlock:b_e,SetUVsBlock:wee,SetValueAction:DFe,ShaderCodeInliner:xv,get ShaderLanguage(){return Qhe},ShaderMaterial:na,get ShaderStage(){return uhe},ShaderStore:de,ShadowDepthWrapper:gTt,ShadowGenerator:pi,ShadowGeneratorSceneComponent:mVe,ShadowLight:Gx,ShadowMapBlock:tHe,ShadowsOptimization:JQ,ShapeBuilder:$vt,ShapeCastResult:v8t,SharpenPostProcess:gT,SheenBlock:hT,SimplexPerlin3DBlock:BHe,SimplicationQueueSceneComponent:yje,SimplificationQueue:_je,SimplificationSettings:dMt,get SimplificationType(){return dde},SineEase:Age,SixDofDragBehavior:V9e,Size:iu,Skeleton:cg,SkeletonViewer:ch,SliderConstraint:a8t,SmartArray:no,SmartArrayNoDuplicate:q2,SmoothStepBlock:PHe,SolidParticle:bde,SolidParticleSystem:XMt,SolidParticleVertex:hYe,Sound:Wd,SoundTrack:N9e,get SourceTextureFormat(){return khe},get Space(){return Pue},SphereBlock:f_e,SphereBuilder:Fvt,SphereDirectedParticleEmitter:rV,SphereParticleEmitter:cD,Spherical:Hp,SphericalHarmonics:bx,SphericalPolynomial:hg,SpotLight:$l,SpringConstraint:c8t,Sprite:bee,SpriteManager:Xm,SpriteMap:H5t,SpritePackedManager:j5t,SpriteSceneComponent:sGe,Stage:Ga,StandardMaterial:et,StandardMaterialDefines:_Be,StandardRenderingPipeline:ls,StartsWith:XFe,StateCondition:IFe,get StencilOperation(){return She},StencilState:K1,StencilStateComposer:dge,StepBlock:xHe,StereoscopicArcRotateCamera:rBe,StereoscopicFreeCamera:sBe,StereoscopicGamepadCamera:nBe,StereoscopicInterlacePostProcess:M2t,StereoscopicInterlacePostProcessI:iBe,StereoscopicScreenUniversalCamera:R2t,StereoscopicUniversalCamera:aBe,StickValues:A2t,StopAnimationAction:NFe,StopSoundAction:UFe,StorageBuffer:WB,get StorageTextureAccess(){return phe},get StoreOp(){return whe},StringDictionary:aZ,StringTools:s_t,SubEmitter:Tv,get SubEmitterType(){return Ade},SubMesh:wl,SubSurfaceBlock:cw,SubSurfaceSceneComponent:rqe,SubtractBlock:yHe,SurfaceMagnetismBehavior:v2t,SwitchBooleanAction:PFe,get SwitchInput(){return Cue},TAARenderingPipeline:a3,TBNBlock:uT,TGATools:gKe,Tags:Br,TargetCamera:pa,TargetedAnimation:C9e,TeleportInBlock:Hje,TeleportOutBlock:jje,TestBase64DataUrl:o9e,TextFileAssetTask:VJe,Texture:xe,get TextureAspect(){return she},TextureAssetTask:KJe,TextureBlock:jk,get TextureDimension(){return the},get TextureFormat(){return nhe},TextureOptimization:qQ,TexturePacker:p0,TexturePackerFrame:ide,get TextureSampleType(){return fhe},TextureSampler:fge,TextureTools:Lke,get TextureUsage(){return ihe},get TextureViewDimension(){return rhe},ThinEngine:bi,ThinRenderTargetTexture:uTt,ThinTexture:lv,TiledBoxBuilder:Kvt,TiledPlaneBuilder:Wvt,get TimerState(){return Xhe},TmpColors:ts,TmpVectors:se,ToGammaSpace:tP,ToHalfFloat:Fm,ToLinearSpace:zB,TonemapPostProcess:cRt,get TonemappingOperator(){return Ude},Tools:Me,TorusBlock:m_e,TorusBuilder:G2t,TorusKnotBuilder:Hvt,TouchCamera:Pge,TrailMesh:Qk,Trajectory:Ws,TrajectoryClassifier:MZ,TranscodeAsync:bZ,get TranscodeTarget(){return cP},TransformBlock:vZ,TransformFeedbackBoundingHelper:uv,TransformNode:_t,TranslationBlock:Bje,TriPlanarBlock:Ree,TrigonometryBlock:U1e,get TrigonometryBlockOperations(){return xo},TubeBuilder:qvt,TwirlBlock:JKe,UncompressPIZ:UKe,UncompressPXR:kKe,UncompressRAW:q1e,UncompressRLE:BKe,UncompressZIP:tde,UniformBuffer:zt,UniversalCamera:Vx,UnregisterAllMaterialPlugins:Hge,UnregisterMaterialPlugin:U2t,UploadContent:X1e,UploadEnvLevelsAsync:m1e,UploadEnvSpherical:uee,UploadLevelsAsync:Vk,UtilityLayerRenderer:is,VRCameraMetrics:nT,VRDeviceOrientationArcRotateCamera:pBe,VRDeviceOrientationFreeCamera:WJ,VRDeviceOrientationGamepadCamera:mBe,VRDistortionCorrectionPostProcess:Vue,VRExperienceHelper:t6,VRMultiviewToSingleviewPostProcess:fBe,ValidatedNativeDataStream:zke,ValueCondition:il,Vector2:we,Vector2ToFixed:pje,Vector3:D,Vector3ToFixed:mje,Vector4:mt,Vector4ToFixed:gje,VectorConverterBlock:Pje,VectorMergerBlock:jB,VectorSplitterBlock:gHe,VertexAnimationBaker:f2t,VertexBuffer:$,VertexData:at,VertexDataMaterialInfo:GB,get VertexFormat(){return The},VertexOutputBlock:HB,get VertexStepMode(){return Mhe},VideoDome:vee,VideoRecorder:Zk,VideoTexture:yh,ViewDirectionBlock:r_e,Viewport:uc,VirtualJoystick:ri,VirtualJoysticksCamera:oBe,VolumetricLightScatteringPostProcess:tf,VoronoiNoiseBlock:jHe,Wav2Decode:OKe,WaveBlock:OHe,get WaveBlockKind(){return sde},WebGL2ParticleSystem:JXe,WebGL2ShaderProcessor:p9e,WebGLDataBuffer:rw,WebGLHardwareTexture:tT,WebGLPipelineContext:t9e,WebGPUCacheBindGroups:Hs,WebGPUCacheRenderPipeline:Gn,WebGPUCacheRenderPipelineTree:e0,WebGPUCacheSampler:By,WebGPUDataBuffer:jke,WebGPUDrawContext:Wz,WebGPUEngine:Oi,WebGPURenderTargetWrapper:Yke,WebGPUTintWASM:Yh,WebRequest:On,WebXRAbstractFeature:gl,WebXRAbstractMotionController:lT,WebXRAnchorSystem:pP,WebXRBackgroundRemover:gP,WebXRCamera:nw,WebXRControllerComponent:id,WebXRControllerMovement:Iv,WebXRControllerPhysics:_P,WebXRControllerPointerSelection:eg,WebXRDefaultExperience:_ee,WebXRDefaultExperienceOptions:Ayt,WebXRDepthSensing:TP,WebXRDomOverlay:bP,WebXREnterExitUI:gee,WebXREnterExitUIButton:_Ue,WebXREnterExitUIOptions:yyt,WebXRExperienceHelper:pee,WebXREyeTracking:SP,WebXRFeatureName:wr,WebXRFeaturePointSystem:yP,WebXRFeaturesManager:Yn,WebXRGenericHandController:Cet,WebXRGenericTriggerMotionController:aw,WebXRHTCViveMotionController:u6,WebXRHand:vUe,get WebXRHandJoint(){return jhe},WebXRHandTracking:Bs,WebXRHitTest:vP,WebXRHitTestLegacy:Rv,WebXRImageTracking:AP,WebXRInput:mUe,WebXRInputSource:pUe,WebXRLayerRenderTargetTextureProvider:KJ,WebXRLayers:EP,WebXRLightEstimation:CP,WebXRManagedOutputCanvas:vBe,WebXRManagedOutputCanvasOptions:wz,WebXRMeshDetector:xP,WebXRMicrosoftMixedRealityController:Pv,WebXRMotionControllerManager:ll,WebXRMotionControllerTeleportation:PS,get WebXRNearControllerMode(){return Khe},WebXRNearInteraction:tg,WebXROculusTouchMotionController:m0,WebXRPlaneDetector:mP,WebXRProfiledMotionController:fUe,WebXRRawCameraAccess:RP,WebXRSessionManager:Dz,WebXRSpaceWarp:MP,WebXRSpaceWarpRenderTargetTextureProvider:bet,get WebXRState(){return Qde},get WebXRTrackingState(){return $de},WebXRWalkingLocomotion:r$,WeightedSound:F9e,WorkerPool:iUe,WorleyNoise3DBlock:s_e,XRSpaceWarpRenderTarget:Aet,get Xbox360Button(){return Bue},get Xbox360Dpad(){return kue},Xbox360Pad:H9e,get XboxInput(){return bue},_BabylonLoaderRegistered:tAt,_BasisTextureLoader:xKe,_CommonDispose:Fge,_CommonInit:Nge,_CreationDataStorage:Sge,_DDSTextureLoader:eUe,_ENVTextureLoader:tUe,_ExrTextureLoader:GKe,_GetCompatibleTextureLoader:bJ,_HDRTextureLoader:vKe,_InstancesBatch:Due,_KTXTextureLoader:sUe,_MeshCollisionData:R9e,_OcclusionDataStorage:Mke,_PrimaryIsoTriangle:c1e,_TGATextureLoader:_Ke,_TimeToken:Pke,_UpdateRGBDAsync:Nke,_forceSceneHelpersToBundle:byt,_forceTransformFeedbackToBundle:f3t,_injectLTSFileTools:l9e,_staticOffsetValueColor3:sge,_staticOffsetValueColor4:nge,_staticOffsetValueQuaternion:ege,_staticOffsetValueSize:rge,_staticOffsetValueVector2:ige,_staticOffsetValueVector3:tge,addClipPlaneUniforms:fo,allocateAndCopyTypedBuffer:cZ,anaglyphPixelShader:aZe,anaglyphPixelShaderWGSL:cZe,appendSceneAsync:cyt,backgroundPixelShader:IWe,backgroundPixelShaderWGSL:VGe,backgroundVertexShader:JGe,backgroundVertexShaderWGSL:pGe,bilateralBlurPixelShader:uqe,bilateralBlurPixelShaderWGSL:bqe,bilateralBlurQualityPixelShader:fqe,bilateralBlurQualityPixelShaderWGSL:Eqe,bindClipPlane:Xa,blackAndWhitePixelShader:eZe,blackAndWhitePixelShaderWGSL:rZe,bloomMergePixelShader:P$e,bloomMergePixelShaderWGSL:L$e,bonesDeclaration:RBe,bonesDeclarationWGSL:qBe,bonesVertex:WBe,bonesVertexWGSL:fke,boundingBoxRendererPixelShader:jqe,boundingBoxRendererPixelShaderWGSL:qqe,boundingBoxRendererVertexShader:Qqe,boundingBoxRendererVertexShaderWGSL:tJe,bumpFragment:hKe,bumpFragmentFunctions:lKe,bumpFragmentFunctionsWGSL:HWe,bumpFragmentMainFunctions:nKe,bumpFragmentMainFunctionsWGSL:GWe,bumpFragmentWGSL:YWe,captureEquirectangularFromScene:gPt,chromaticAberrationPixelShader:HYe,chromaticAberrationPixelShaderWGSL:m$e,circleOfConfusionPixelShader:S$e,circleOfConfusionPixelShaderWGSL:M$e,className:F_t,clipPlaneFragment:OUe,clipPlaneFragmentDeclaration:wUe,clipPlaneFragmentDeclarationWGSL:QUe,clipPlaneFragmentWGSL:qUe,clipPlaneVertex:WUe,clipPlaneVertexDeclaration:zUe,clipPlaneVertexDeclarationWGSL:sze,clipPlaneVertexWGSL:oze,colorCorrectionPixelShader:vZe,colorCorrectionPixelShaderWGSL:AZe,colorPixelShader:DWe,colorPixelShaderWGSL:hXe,colorVertexShader:NWe,colorVertexShaderWGSL:pXe,computeMaxExtents:gMt,convolutionPixelShader:dZe,convolutionPixelShaderWGSL:mZe,copyTextureToTexturePixelShader:met,copyTextureToTexturePixelShaderWGSL:vet,createDetailMapPlugin:CTt,createPBRAnisotropicPlugin:_Tt,createPBRBRDFPlugin:vTt,createPBRClearCoatPlugin:yTt,createPBRIridescencePlugin:xTt,createPBRSheenPlugin:ATt,createPBRSubSurfacePlugin:bTt,createYieldingScheduler:S9e,defaultPixelShader:rje,defaultPixelShaderWGSL:cje,defaultVertexShader:aje,defaultVertexShaderWGSL:dje,depthBoxBlurPixelShader:ZVe,depthBoxBlurPixelShaderWGSL:LVe,depthOfFieldMergePixelShader:v$e,depthOfFieldMergePixelShaderWGSL:A$e,depthPixelShader:cVe,depthPixelShaderWGSL:Oqe,depthVertexShader:dVe,depthVertexShaderWGSL:Bqe,displayPassPixelShader:GZe,displayPassPixelShaderWGSL:HZe,editableInPropertyPage:Jt,expandToProperty:Fe,extractHighlightsPixelShader:F$e,extractHighlightsPixelShaderWGSL:U$e,extractMinAndMax:JS,extractMinAndMaxIndexed:T9e,filterPixelShader:PZe,filterPixelShaderWGSL:LZe,fogFragmentDeclaration:CWe,fogFragmentDeclarationWGSL:NGe,fxaaPixelShader:G$e,fxaaPixelShaderWGSL:Y$e,fxaaVertexShader:H$e,fxaaVertexShaderWGSL:Z$e,geometryPixelShader:DYe,geometryPixelShaderWGSL:zqe,geometryVertexShader:NYe,geometryVertexShaderWGSL:Wqe,getRichTypeFromValue:wet,glowBlurPostProcessPixelShader:Aze,glowBlurPostProcessPixelShaderWGSL:Dze,glowMapGenerationPixelShader:BUe,glowMapGenerationPixelShaderWGSL:tze,glowMapGenerationVertexShader:jUe,glowMapGenerationVertexShaderWGSL:uze,glowMapMergePixelShader:fze,glowMapMergePixelShaderWGSL:Sze,glowMapMergeVertexShader:_ze,glowMapMergeVertexShaderWGSL:Rze,grainPixelShader:c$e,grainPixelShaderWGSL:d$e,helperFunctions:MUe,helperFunctionsWGSL:Wke,highlightsPixelShader:FZe,highlightsPixelShaderWGSL:UZe,imageProcessingDeclaration:nWe,imageProcessingDeclarationWGSL:xGe,imageProcessingFunctions:xWe,imageProcessingFunctionsWGSL:DGe,imageProcessingPixelShader:r$e,imageProcessingPixelShaderWGSL:e$e,importAnimationsAsync:hyt,inlineScheduler:kk,kernelBlurPixelShader:MQe,kernelBlurPixelShaderWGSL:LQe,kernelBlurVertexShader:PQe,kernelBlurVertexShaderWGSL:FQe,layerPixelShader:Nze,layerPixelShaderWGSL:Vze,layerVertexShader:kze,layerVertexShaderWGSL:Kze,lensFlarePixelShader:Yze,lensFlarePixelShaderWGSL:eVe,lensFlareVertexShader:Zze,lensFlareVertexShaderWGSL:rVe,lightFragment:TWe,lightFragmentDeclaration:lWe,lightFragmentWGSL:kGe,lightUboDeclaration:hWe,lightUboDeclarationWGSL:CGe,lightVxFragmentDeclaration:KGe,lightVxUboDeclaration:XGe,lightVxUboDeclarationWGSL:lGe,lightsFragmentFunctions:pWe,lightsFragmentFunctionsWGSL:TGe,linePixelShader:sJe,linePixelShaderWGSL:uJe,lineVertexShader:oJe,lineVertexShaderWGSL:fJe,loadAssetContainerAsync:uyt,loadSceneAsync:lyt,makeAsyncFunction:e2t,makeSyncFunction:E9e,meshUVSpaceRendererFinaliserPixelShader:IXe,meshUVSpaceRendererFinaliserPixelShaderWGSL:XXe,meshUVSpaceRendererFinaliserVertexShader:DXe,meshUVSpaceRendererFinaliserVertexShaderWGSL:$Xe,meshUVSpaceRendererMaskerPixelShader:TXe,meshUVSpaceRendererMaskerPixelShaderWGSL:KXe,meshUVSpaceRendererMaskerVertexShader:CXe,meshUVSpaceRendererMaskerVertexShaderWGSL:VXe,meshUVSpaceRendererPixelShader:xXe,meshUVSpaceRendererPixelShaderWGSL:kXe,meshUVSpaceRendererVertexShader:_Xe,meshUVSpaceRendererVertexShaderWGSL:NXe,morphTargetsVertex:zBe,morphTargetsVertexDeclaration:OBe,morphTargetsVertexDeclarationWGSL:ske,morphTargetsVertexGlobal:BBe,morphTargetsVertexGlobalDeclaration:wBe,morphTargetsVertexGlobalDeclarationWGSL:tke,morphTargetsVertexGlobalWGSL:oke,morphTargetsVertexWGSL:uke,motionBlurPixelShader:SZe,motionBlurPixelShaderWGSL:MZe,nativeOverride:l_,normalizeEnvInfo:Gz,outlinePixelShader:gJe,outlinePixelShaderWGSL:bJe,outlineVertexShader:yJe,outlineVertexShaderWGSL:EJe,packingFunctions:aVe,packingFunctionsWGSL:vVe,particlesPixelShader:mYe,particlesPixelShaderWGSL:bYe,particlesVertexShader:vYe,particlesVertexShaderWGSL:EYe,passCubePixelShader:UQe,passCubePixelShaderWGSL:HQe,passPixelShader:uZ,passPixelShaderWGSL:GQe,pbrPixelShader:pKe,pbrPixelShaderWGSL:ZWe,pbrVertexShader:tKe,pbrVertexShaderWGSL:kWe,pickingPixelShader:EBe,pickingPixelShaderWGSL:QBe,pickingVertexShader:jBe,pickingVertexShaderWGSL:gke,postprocessVertexShader:Z9e,postprocessVertexShaderWGSL:SQe,prepareDefinesForClipPlanes:I9e,prepareStringDefinesForClipPlanes:t3,reflectionFunction:iWe,reflectionFunctionWGSL:_Ge,registerSceneLoaderPlugin:sD,rgbdDecodePixelShader:eet,rgbdDecodePixelShaderWGSL:oet,rgbdEncodePixelShader:set,rgbdEncodePixelShaderWGSL:det,rsmFullGlobalIlluminationPixelShader:yqe,rsmFullGlobalIlluminationPixelShaderWGSL:wqe,rsmGlobalIlluminationPixelShader:gqe,rsmGlobalIlluminationPixelShaderWGSL:Rqe,runCoroutine:bge,runCoroutineAsync:IJ,runCoroutineSync:RJ,screenSpaceReflection2BlurCombinerPixelShader:dQe,screenSpaceReflection2BlurCombinerPixelShaderWGSL:AQe,screenSpaceReflection2BlurPixelShader:cQe,screenSpaceReflection2BlurPixelShaderWGSL:vQe,screenSpaceReflection2PixelShader:aQe,screenSpaceReflection2PixelShaderWGSL:mQe,serialize:X,serializeAsCameraReference:GFe,serializeAsColor3:br,serializeAsColor4:jw,serializeAsColorCurves:zFe,serializeAsFresnelParameters:Kw,serializeAsImageProcessingConfiguration:Jme,serializeAsMatrix:xJ,serializeAsMeshReference:Hw,serializeAsQuaternion:VFe,serializeAsTexture:ii,serializeAsVector2:nz,serializeAsVector3:Pn,setAndStartTimer:vB,setStereoscopicAnaglyphRigMode:Rz,setStereoscopicRigMode:Iz,setVRRigMode:GJ,shadowMapFragment:UVe,shadowMapFragmentSoftTransparentShadow:eGe,shadowMapFragmentSoftTransparentShadowWGSL:FVe,shadowMapFragmentWGSL:AVe,shadowMapPixelShader:GVe,shadowMapPixelShaderWGSL:SVe,shadowMapVertexMetric:HVe,shadowMapVertexMetricWGSL:MVe,shadowMapVertexShader:YVe,shadowMapVertexShaderWGSL:PVe,shadowsFragmentFunctions:_We,shadowsFragmentFunctionsWGSL:IGe,shadowsVertex:$Ge,shadowsVertexWGSL:hGe,sharpenPixelShader:zYe,sharpenPixelShaderWGSL:a$e,spritesPixelShader:RJe,spritesPixelShaderWGSL:OJe,spritesVertexShader:wJe,spritesVertexShaderWGSL:BJe,ssao2PixelShader:ZYe,ssao2PixelShaderWGSL:eQe,ssaoCombinePixelShader:YYe,ssaoCombinePixelShaderWGSL:rQe,tonemapPixelShader:YZe,tonemapPixelShaderWGSL:ZZe,vrDistortionCorrectionPixelShader:YQe,vrDistortionCorrectionPixelShaderWGSL:ZQe},Symbol.toStringTag,{value:"Module"}));function XPt(s){return{all:s=s||new Map,on:function(e,t){var i=s.get(e);i?i.push(t):s.set(e,[t])},off:function(e,t){var i=s.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var i=s.get(e);i&&i.slice().map(function(r){r(t)}),(i=s.get("*"))&&i.slice().map(function(r){r(e,t)})}}}class YPt{constructor(){this.limit=1,this._queue=[],this._running=0,this._count=0}push(e){this._queue.push(e),this._run()}async _run(){if(this._running>=this.limit||this._queue.length===0)return;const e=this._queue.shift();e&&(this._running++,this._count++,e().finally(()=>{this._running--,this._run()}))}}function Y1(s,e=t=>{}){try{s&&s()}catch(t){console.error(t),e(t)}}function Ci(s){return`${Me.RandomId()}`}const t0=s=>Object.prototype.toString.call(s)==="[object Array]",Il=s=>Object.prototype.toString.call(s)==="[object Object]",zf=(s,e)=>{const t={[rt.Boolean]:"boolean",[rt.Number]:"number",[rt.String]:"string",[rt.Array]:"array",[rt.Object]:"object"}[e];if(t==="boolean"){if(typeof s=="boolean")return s;if(typeof s=="string"){if(s.toLocaleLowerCase()==="true")return!0;if(s.toLocaleLowerCase()==="false")return!1}return!!s}if(t==="number"){if(typeof s=="number")return s;let i=Number(s);return!isNaN(i)||(i=parseFloat(s),!isNaN(i))?i:0}if(t==="string")return typeof s=="string"?s:s==null?"":String(s);if(t==="array"){if(t0(s))return s;let i=[];try{typeof s=="string"&&(s=JSON.parse(s)),t0(s)&&(i=s)}catch(r){console.error(r)}return i}if(t==="object"){if(Il(s))return s;let i={};try{typeof s=="string"&&(s=JSON.parse(s)),Il(s)&&(i=s)}catch(r){console.error(r)}return i}},wMe=(s,e)=>zf(s,QPt(e)),vV=(s,e)=>{if(e===J.String||e===J.Color3||e===J.Color4)return zf(s,rt.String);if(e===J.Array)return zf(s,rt.Array);if(e===J.Object)return zf(s,rt.Object);if(e===J.Number)return zf(s,rt.Number);if(e===J.Boolean)return zf(s,rt.Boolean)},QPt=s=>({string:rt.String,integer:rt.Number,float:rt.Number,bool:rt.Boolean,array:rt.Array,object:rt.Object})[s]??rt.String,$Pt=s=>({[J.String]:rt.String,[J.Number]:rt.Number,[J.Boolean]:rt.Boolean,[J.Color3]:rt.String,[J.Color4]:rt.String,[J.Array]:rt.Array,[J.Object]:rt.Object})[s]??rt.String,Qne=s=>({[rt.String]:J.String,[rt.Number]:J.Number,[rt.Boolean]:J.Boolean,[rt.Array]:J.Array,[rt.Object]:J.Object})[s]??J.Unknown;function ZPt(s){switch(s){case J.Number:return 0;case J.String:return"";case J.Boolean:return!1;case J.Null:return null;case J.Void:return;case J.Array:return[];case J.Object:return{}}}var ttt=typeof global=="object"&&global&&global.Object===Object&&global,qPt=typeof self=="object"&&self&&self.Object===Object&&self,Ag=ttt||qPt||Function("return this")(),Ex=Ag.Symbol,itt=Object.prototype,JPt=itt.hasOwnProperty,ewt=itt.toString,b9=Ex?Ex.toStringTag:void 0;function twt(s){var e=JPt.call(s,b9),t=s[b9];try{s[b9]=void 0;var i=!0}catch{}var r=ewt.call(s);return i&&(e?s[b9]=t:delete s[b9]),r}var iwt=Object.prototype,rwt=iwt.toString;function swt(s){return rwt.call(s)}var nwt="[object Null]",awt="[object Undefined]",DMe=Ex?Ex.toStringTag:void 0;function vD(s){return s==null?s===void 0?awt:nwt:DMe&&DMe in Object(s)?twt(s):swt(s)}function yD(s){return s!=null&&typeof s=="object"}var owt="[object Symbol]";function rtt(s){return typeof s=="symbol"||yD(s)&&vD(s)==owt}function lwt(s,e){for(var t=-1,i=s==null?0:s.length,r=Array(i);++t-1&&s%1==0&&s-1&&s%1==0&&s<=Hwt}function htt(s){return s!=null&&utt(s.length)&&!att(s)}var jwt=Object.prototype;function t2e(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||jwt;return s===t}function Xwt(s,e){for(var t=-1,i=Array(s);++t-1}function tLt(s,e){var t=this.__data__,i=Jee(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}function l3(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e(s.Grad="Grad",s.OutLine="OutLine",s))(Su||{});function HOt(s,e){zi.ShadersStore[s+"VertexShader"]=`\r precision highp float;\r //attribute\r attribute vec3 position;\r attribute vec2 uv;\r attribute vec3 normal;\r //uniform\r uniform mat4 worldViewProjection;\r //varying\r varying vec3 vPosition;\r varying vec2 vUV;\r varying vec3 vNormal;\r void main(void) {\r gl_Position = worldViewProjection*vec4(position,1.0);\r vPosition = position;\r vUV = uv;\r vNormal = normal;\r }\r `,zi.ShadersStore[s+"FragmentShader"]=`\r precision highp float;\r varying vec3 vPosition;\r varying vec3 vNormal;\r uniform float distance;\r uniform vec3 changeColor;\r uniform vec3 center;\r uniform float power;\r uniform float k;\r uniform vec3 viewPoint;\r float distanceTwoVec3(vec3 p1,vec3 p2){\r float d = sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)+(p1.z-p2.z)*(p1.z-p2.z));\r return d;\r }\r void main(void) {\r float modelDot = abs(dot(viewPoint,vNormal)/(length(viewPoint)*length(vNormal)));\r float alpha = distanceTwoVec3(center,vPosition)*k /distance;\r vec3 color = changeColor;\r alpha = modelDot * pow(alpha,power);\r gl_FragColor = vec4(color,alpha);\r }\r `;let t=new na("effectGlShader"+s,e,{vertex:s,fragment:s},{attributes:["normal","position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0,needAlphaTesting:!0});return t.onBind=i=>{const r=i.getBoundingInfo().boundingBox,n=D.Normalize(r.centerWorld),a=D.Distance(r.centerWorld,r.maximumWorld);t.setFloat("distance",a),t.setVector3("center",n),t.setVector3("viewPoint",D.Normalize(i.getScene().activeCamera.position)),t.onBind=null},t.setFloat("distance",20),t.setVector3("center",new D(10,10*Math.random(),10)),t.setVector3("viewPoint",new D(10,10*Math.random(),10)),t}function jOt(s,e){return zi.ShadersStore["gradient"+s+"VertexShader"]=`\r precision highp float;\r //attribute\r attribute vec3 position;\r attribute vec2 uv;\r attribute vec3 normal;\r //uniform\r uniform mat4 worldViewProjection;\r //varying\r varying vec3 vPosition;\r varying vec2 vUV;\r varying vec3 vNormal;\r void main(void) {\r gl_Position = worldViewProjection*vec4(position,1.0);\r vPosition = position;\r vUV = uv;\r vNormal = normal;\r }\r `,zi.ShadersStore["gradient"+s+"FragmentShader"]=`\r precision highp float;\r varying vec3 vPosition;\r float distanceTwoVec3(vec3 p1,vec3 p2){\r float d = sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)+(p1.z-p2.z)*(p1.z-p2.z));\r return d;\r }\r uniform vec3 mainColor;\r uniform float maxHeight;\r uniform float minHeight;\r uniform float alphaK;\r void main(void) {\r float height = maxHeight - minHeight;\r vec3 color = mainColor;\r float alpha = (vPosition.y-minHeight)/height;\r gl_FragColor = vec4(color,alphaK+pow(alpha,0.5)*alpha*(1.0-alphaK));\r }\r `,new na("effectGradAlpha"+s,e,{vertex:"gradient"+s,fragment:"gradient"+s},{attributes:["normal","position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0,needAlphaTesting:!0})}var Mtt={exports:{}};const XOt=rNe(jPt);(function(s,e){(function(i,r){s.exports=r(XOt)})(typeof self<"u"?self:Xt,t=>(()=>{var i={"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../dev/sharedUiComponents/dist/colorPicker/colorPicker.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.color-picker-container { width: 320px; height: 300px; background-color: white; display: grid; grid-template-columns: 100%; grid-template-rows: 50% 50px 60px 40px 1fr auto; font-family: "acumin-pro-condensed"; font-weight: normal; font-size: 14px; } .color-picker-container.with-hints { height: 380px; } .color-picker-container .color-picker-saturation { grid-row: 1; grid-column: 1; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; position: relative; cursor: pointer; } .color-picker-container .color-picker-saturation .color-picker-saturation-white { grid-row: 1; grid-column: 1; background: -webkit-linear-gradient(to right, #fff, rgba(255, 255, 255, 0)); background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0)); } .color-picker-container .color-picker-saturation .color-picker-saturation-black { grid-row: 1; grid-column: 1; background: -webkit-linear-gradient(to top, #000, rgba(0, 0, 0, 0)); background: linear-gradient(to top, #000, rgba(0, 0, 0, 0)); } .color-picker-container .color-picker-saturation .color-picker-saturation-cursor { pointer-events: none; width: 4px; height: 4px; box-shadow: 0 0 0 1.5px #fff, inset 0 0 1px 1px rgba(0, 0, 0, 0.3), 0 0 1px 2px rgba(0, 0, 0, 0.4); border-radius: 50%; transform: translate(-2px, -2px); position: absolute; } .color-picker-container .color-picker-hue { grid-row: 2; grid-column: 1; display: grid; margin: 10px; grid-template-columns: 24% 76%; grid-template-rows: 100%; } .color-picker-container .color-picker-hue .color-picker-hue-color { grid-row: 1; grid-column: 1; align-self: center; justify-self: center; width: 30px; height: 30px; border-radius: 15px; border: 1px solid black; } .color-picker-container .color-picker-hue .color-picker-hue-slider { grid-row: 1; grid-column: 2; align-self: center; height: 16px; position: relative; cursor: pointer; background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%); background: -webkit-linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%); } .color-picker-container .color-picker-hue .color-picker-hue-slider .color-picker-hue-cursor { pointer-events: none; width: 8px; height: 18px; transform: translate(-4px, -2px); background-color: rgb(248, 248, 248); box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37); position: absolute; } .color-picker-container .color-picker-component { display: grid; margin: 5px; grid-template-columns: 100%; grid-template-rows: 50% 50%; } .color-picker-container .color-picker-component .color-picker-component-value { justify-self: center; align-self: center; grid-row: 1; grid-column: 1; margin-bottom: 4px; } .color-picker-container .color-picker-component .color-picker-component-value input { width: 50px; } .color-picker-container .color-picker-component .color-picker-component-label { justify-self: center; align-self: center; grid-row: 2; grid-column: 1; color: black; } .color-picker-container .color-picker-rgb { grid-row: 3; grid-column: 1; display: grid; margin: 10px; grid-template-columns: 20% 6.66% 20% 6.66% 20% 6.66% 20%; grid-template-rows: 100%; } .color-picker-container .red { grid-row: 1; grid-column: 1; } .color-picker-container .green { grid-row: 1; grid-column: 3; } .color-picker-container .blue { grid-row: 1; grid-column: 5; } .color-picker-container .alpha { grid-row: 1; grid-column: 7; } .color-picker-container .alpha.grayed { opacity: 0.5; } .color-picker-container .color-picker-hex { grid-row: 4; grid-column: 1; display: grid; grid-template-columns: 20% 80%; grid-template-rows: 100%; } .color-picker-container .color-picker-hex .color-picker-hex-label { justify-self: center; align-self: center; grid-row: 1; grid-column: 1; margin-left: 10px; color: black; } .color-picker-container .color-picker-hex .color-picker-hex-value { justify-self: left; align-self: center; grid-row: 1; grid-column: 2; margin-left: 10px; margin-right: 10px; } .color-picker-container .color-picker-hex .color-picker-hex-value input { width: 70px; } .color-picker-container .color-picker-warning { color: black; font-size: 11px; padding: 4px; justify-self: left; align-self: center; grid-row: 6; grid-column: 1; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/colorPicker/colorPicker.scss"],names:[],mappings:"AAAA;EACI,YAAA;EACA,aAAA;EACA,uBAAA;EACA,aAAA;EACA,2BAAA;EACA,+CAAA;EACA,mCAAA;EACA,mBAAA;EACA,eAAA;AACJ;AACI;EACI,aAAA;AACR;AAEI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;EACA,kBAAA;EACA,eAAA;AAAR;AAEQ;EACI,WAAA;EACA,cAAA;EAEA,2EAAA;EACA,mEAAA;AADZ;AAIQ;EACI,WAAA;EACA,cAAA;EAEA,mEAAA;EACA,2DAAA;AAHZ;AAMQ;EACI,oBAAA;EACA,UAAA;EACA,WAAA;EACA,kGACI;EAGJ,kBAAA;EACA,gCAAA;EACA,kBAAA;AAPZ;AAWI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,YAAA;EACA,8BAAA;EACA,wBAAA;AATR;AAWQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,oBAAA;EACA,WAAA;EACA,YAAA;EACA,mBAAA;EACA,uBAAA;AATZ;AAYQ;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EAEA,2GAAA;EACA,mHAAA;AAXZ;AAaY;EACI,oBAAA;EACA,UAAA;EACA,YAAA;EACA,gCAAA;EACA,oCAAA;EACA,2CAAA;EACA,kBAAA;AAXhB;AAgBI;EACI,aAAA;EACA,WAAA;EACA,2BAAA;EACA,2BAAA;AAdR;AAgBQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;AAdZ;AAgBY;EACI,WAAA;AAdhB;AAkBQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,YAAA;AAhBZ;AAoBI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,YAAA;EACA,wDAAA;EACA,wBAAA;AAlBR;AAqBI;EACI,WAAA;EACA,cAAA;AAnBR;AAsBI;EACI,WAAA;EACA,cAAA;AApBR;AAuBI;EACI,WAAA;EACA,cAAA;AArBR;AAwBI;EACI,WAAA;EACA,cAAA;AAtBR;AAwBQ;EACI,YAAA;AAtBZ;AA0BI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,8BAAA;EACA,wBAAA;AAxBR;AA0BQ;EACI,oBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,YAAA;AAxBZ;AA2BQ;EACI,kBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,kBAAA;AAzBZ;AA2BY;EACI,WAAA;AAzBhB;AA8BI;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,kBAAA;EACA,kBAAA;EACA,WAAA;EACA,cAAA;AA5BR",sourcesContent:[`.color-picker-container {\r width: 320px;\r height: 300px;\r background-color: white;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 50% 50px 60px 40px 1fr auto;\r font-family: "acumin-pro-condensed";\r font-weight: normal;\r font-size: 14px;\r \r &.with-hints {\r height: 380px;\r }\r \r .color-picker-saturation {\r grid-row: 1;\r grid-column: 1;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r position: relative;\r cursor: pointer;\r \r .color-picker-saturation-white {\r grid-row: 1;\r grid-column: 1;\r \r background: -webkit-linear-gradient(to right, #fff, rgba(255, 255, 255, 0));\r background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0));\r }\r \r .color-picker-saturation-black {\r grid-row: 1;\r grid-column: 1;\r \r background: -webkit-linear-gradient(to top, #000, rgba(0, 0, 0, 0));\r background: linear-gradient(to top, #000, rgba(0, 0, 0, 0));\r }\r \r .color-picker-saturation-cursor {\r pointer-events: none;\r width: 4px;\r height: 4px;\r box-shadow:\r 0 0 0 1.5px #fff,\r inset 0 0 1px 1px rgba(0, 0, 0, 0.3),\r 0 0 1px 2px rgba(0, 0, 0, 0.4);\r border-radius: 50%;\r transform: translate(-2px, -2px);\r position: absolute;\r }\r }\r \r .color-picker-hue {\r grid-row: 2;\r grid-column: 1;\r display: grid;\r margin: 10px;\r grid-template-columns: 24% 76%;\r grid-template-rows: 100%;\r \r .color-picker-hue-color {\r grid-row: 1;\r grid-column: 1;\r align-self: center;\r justify-self: center;\r width: 30px;\r height: 30px;\r border-radius: 15px;\r border: 1px solid black;\r }\r \r .color-picker-hue-slider {\r grid-row: 1;\r grid-column: 2;\r align-self: center;\r height: 16px;\r position: relative;\r cursor: pointer;\r \r background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\r background: -webkit-linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\r \r .color-picker-hue-cursor {\r pointer-events: none;\r width: 8px;\r height: 18px;\r transform: translate(-4px, -2px);\r background-color: rgb(248, 248, 248);\r box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);\r position: absolute;\r }\r }\r }\r \r .color-picker-component {\r display: grid;\r margin: 5px;\r grid-template-columns: 100%;\r grid-template-rows: 50% 50%;\r \r .color-picker-component-value {\r justify-self: center;\r align-self: center;\r grid-row: 1;\r grid-column: 1;\r margin-bottom: 4px;\r \r input {\r width: 50px;\r }\r }\r \r .color-picker-component-label {\r justify-self: center;\r align-self: center;\r grid-row: 2;\r grid-column: 1;\r color: black;\r }\r }\r \r .color-picker-rgb {\r grid-row: 3;\r grid-column: 1;\r display: grid;\r margin: 10px;\r grid-template-columns: 20% 6.66% 20% 6.66% 20% 6.66% 20%;\r grid-template-rows: 100%;\r }\r \r .red {\r grid-row: 1;\r grid-column: 1;\r }\r \r .green {\r grid-row: 1;\r grid-column: 3;\r }\r \r .blue {\r grid-row: 1;\r grid-column: 5;\r }\r \r .alpha {\r grid-row: 1;\r grid-column: 7;\r \r &.grayed {\r opacity: 0.5;\r }\r }\r \r .color-picker-hex {\r grid-row: 4;\r grid-column: 1;\r display: grid;\r grid-template-columns: 20% 80%;\r grid-template-rows: 100%;\r \r .color-picker-hex-label {\r justify-self: center;\r align-self: center;\r grid-row: 1;\r grid-column: 1;\r margin-left: 10px;\r color: black;\r }\r \r .color-picker-hex-value {\r justify-self: left;\r align-self: center;\r grid-row: 1;\r grid-column: 2;\r margin-left: 10px;\r margin-right: 10px;\r \r input {\r width: 70px;\r }\r }\r }\r \r .color-picker-warning {\r color: black;\r font-size: 11px;\r padding: 4px;\r justify-self: left;\r align-self: center;\r grid-row: 6;\r grid-column: 1;\r }\r }\r `],sourceRoot:""}]),p.locals={};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/searchBox.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`#graph-search-container { position: absolute; width: 100%; height: 100%; left: 0; top: 0; } #graph-search-container #graph-search-picking-blocker { position: absolute; width: 100%; height: 100%; left: 0; top: 0; cursor: default; } #graph-search-container #graph-search-box { width: 300px; height: 400px; position: absolute; left: calc(50% - 150px); top: calc(50% - 200px); background: rgb(72, 72, 72); border: 2px solid black; z-index: 100; cursor: auto; display: grid; grid-template-rows: auto auto 1fr; } #graph-search-container #graph-search-box .graph-search-box-title { border-bottom: 1px solid rgb(40, 40, 40); margin: 4px; padding-bottom: 4px; color: white; grid-row: 1; } #graph-search-container #graph-search-box .graph-search-box-filter { margin: 4px; padding-bottom: 4px; border-radius: 4px; width: calc(100% - 16px); grid-row: 2; } #graph-search-container #graph-search-box .graph-search-box-list { grid-row: 3; overflow-y: auto; display: flex; flex-direction: column; } #graph-search-container #graph-search-box .graph-search-box-list .graph-search-box-list-item { margin-left: 4px; cursor: pointer; color: white; margin-top: 4px; margin-bottom: 4px; } #graph-search-container #graph-search-box .graph-search-box-list .graph-search-box-list-item:hover { background: rgb(30, 30, 30); } #graph-search-container #graph-search-box .graph-search-box-list .graph-search-box-list-item.selected { background: rgb(230, 230, 230); color: black; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/searchBox.scss"],names:[],mappings:"AAAA;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;AACJ;AACI;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,eAAA;AACR;AAEI;EACI,YAAA;EACA,aAAA;EACA,kBAAA;EACA,uBAAA;EACA,sBAAA;EACA,2BAAA;EACA,uBAAA;EACA,YAAA;EACA,YAAA;EACA,aAAA;EACA,iCAAA;AAAR;AAEQ;EACI,wCAAA;EACA,WAAA;EACA,mBAAA;EACA,YAAA;EACA,WAAA;AAAZ;AAGQ;EACI,WAAA;EACA,mBAAA;EACA,kBAAA;EACA,wBAAA;EACA,WAAA;AADZ;AAIQ;EACI,WAAA;EACA,gBAAA;EACA,aAAA;EACA,sBAAA;AAFZ;AAIY;EACI,gBAAA;EACA,eAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;AAFhB;AAIgB;EACI,2BAAA;AAFpB;AAKgB;EACI,8BAAA;EACA,YAAA;AAHpB",sourcesContent:[`#graph-search-container {\r position: absolute;\r width: 100%;\r height: 100%;\r left: 0;\r top: 0;\r \r #graph-search-picking-blocker {\r position: absolute;\r width: 100%;\r height: 100%;\r left: 0;\r top: 0;\r cursor: default;\r }\r \r #graph-search-box {\r width: 300px;\r height: 400px;\r position: absolute;\r left: calc(50% - 150px);\r top: calc(50% - 200px);\r background: rgb(72, 72, 72);\r border: 2px solid black;\r z-index: 100;\r cursor: auto;\r display: grid;\r grid-template-rows: auto auto 1fr;\r \r .graph-search-box-title {\r border-bottom: 1px solid rgb(40, 40, 40);\r margin: 4px;\r padding-bottom: 4px;\r color: white;\r grid-row: 1;\r }\r \r .graph-search-box-filter {\r margin: 4px;\r padding-bottom: 4px;\r border-radius: 4px;\r width: calc(100% - 16px);\r grid-row: 2;\r }\r \r .graph-search-box-list {\r grid-row: 3;\r overflow-y: auto;\r display: flex;\r flex-direction: column;\r \r .graph-search-box-list-item {\r margin-left: 4px;\r cursor: pointer;\r color: white;\r margin-top: 4px;\r margin-bottom: 4px;\r \r &:hover {\r background: rgb(30, 30, 30);\r }\r \r &.selected {\r background: rgb(230, 230, 230);\r color: black;\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/components/log/log.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`#nme-log-console { background: #333333; height: 120px; box-sizing: border-box; margin: 0; padding: 10px; width: 100%; overflow: hidden; overflow-y: auto; grid-row: 2; grid-column: 3; } #nme-log-console .log { color: white; font-size: 14px; font-family: "Courier New", Courier, monospace; } #nme-log-console .log.error { color: red; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/components/log/log.scss"],names:[],mappings:"AAAA;EACI,mBAAA;EACA,aAAA;EACA,sBAAA;EACA,SAAA;EACA,aAAA;EACA,WAAA;EACA,gBAAA;EACA,gBAAA;EACA,WAAA;EACA,cAAA;AACJ;AACI;EACI,YAAA;EACA,eAAA;EACA,8CAAA;AACR;AACQ;EACI,UAAA;AACZ",sourcesContent:[`#nme-log-console {\r background: #333333;\r height: 120px;\r box-sizing: border-box;\r margin: 0;\r padding: 10px;\r width: 100%;\r overflow: hidden;\r overflow-y: auto;\r grid-row: 2;\r grid-column: 3;\r \r .log {\r color: white;\r font-size: 14px;\r font-family: "Courier New", Courier, monospace;\r \r &.error {\r color: red;\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/components/nodeList/nodeList.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`#nmeNodeList { background: #333333; height: 100%; margin: 0; padding: 0; display: grid; width: 100%; overflow: hidden; } #nmeNodeList .panes { overflow: hidden; } #nmeNodeList .panes .pane { color: white; overflow: hidden; height: 100%; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } #nmeNodeList .panes .pane .filter { display: flex; align-items: stretch; } #nmeNodeList .panes .pane .filter input { width: 100%; margin: 10px 10px 5px 10px; display: block; border: none; padding: 0; border-bottom: solid 1px rgb(51, 122, 183); background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 96%, rgb(51, 122, 183) 4%); background-position: -1000px 0; background-size: 1000px 100%; background-repeat: no-repeat; color: white; } #nmeNodeList .panes .pane .filter input:focus { box-shadow: none; outline: none; background-position: 0 0; } #nmeNodeList .panes .pane .filter input::placeholder { color: gray; } #nmeNodeList .panes .pane .list-container { overflow-x: hidden; overflow-y: auto; height: calc(100% - 32px); } #nmeNodeList .panes .pane .list-container .underline { border-bottom: 0.5px solid rgba(255, 255, 255, 0.5); } #nmeNodeList .panes .pane .list-container .draggableLine { height: 30px; display: grid; align-items: center; justify-items: stretch; background: #222222; cursor: grab; text-align: center; margin: 0; box-sizing: border-box; } #nmeNodeList .panes .pane .list-container .draggableLine:hover { background: rgb(51, 122, 183); color: white; } #nmeNodeList .panes .pane .list-container .nonDraggableLine { height: 30px; display: grid; align-items: center; justify-items: stretch; background: #222222; text-align: center; margin: 0; box-sizing: border-box; } #nmeNodeList .panes .pane .list-container .withButton { height: 30px; position: relative; } #nmeNodeList .panes .pane .list-container .withButton .icon { position: absolute; right: 4px; top: 5px; } #nmeNodeList .panes .pane .list-container .withButton .icon:hover { cursor: pointer; } #nmeNodeList .panes .pane .list-container .withButton .icon .img { height: 17px; width: 17px; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine { height: 30px; display: grid; align-items: center; justify-items: stretch; padding-bottom: 5px; position: absolute; right: 0px; top: 2px; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine input[type=file] { display: none; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine .file-upload { background: transparent; border: transparent; padding: 15px 200px; opacity: 0.9; cursor: pointer; text-align: center; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine .file-upload:hover { opacity: 1; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine .file-upload:active { transform: scale(0.98); transform-origin: 0.5 0.5; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button { background: transparent; border: transparent; margin: 5px 10px 5px 10px; color: white; padding: 4px 5px; opacity: 0.9; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button:hover { opacity: 0; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button:active { background: transparent; } #nmeNodeList .panes .pane .list-container .withButton .buttonLine button:focus { border: transparent; outline: 0px; } #nmeNodeList .panes .pane .list-container .paneContainer { margin-top: 3px; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content { grid-row: 1; grid-column: 1; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header { display: grid; grid-template-columns: 1fr auto; background: #555555; height: 30px; padding-right: 5px; cursor: pointer; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header .title { border-left: 3px solid transparent; padding-left: 5px; grid-column: 1; display: flex; align-items: center; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header .collapse { grid-column: 2; display: flex; align-items: center; justify-items: center; transform-origin: center; } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .header .collapse.closed { transform: rotate(180deg); } #nmeNodeList .panes .pane .list-container .paneContainer .paneContainer-content .paneList > div:not(:last-child) { border-bottom: 1px solid rgba(255, 255, 255, 0.3); }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/components/nodeList/nodeList.scss"],names:[],mappings:"AAAA;EACI,mBAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,aAAA;EACA,WAAA;EACA,gBAAA;AACJ;AACI;EACI,gBAAA;AACR;AACQ;EACI,YAAA;EAEA,gBAAA;EACA,YAAA;EAEA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AADZ;AAGY;EACI,aAAA;EACA,oBAAA;AADhB;AAGgB;EACI,WAAA;EACA,0BAAA;EACA,cAAA;EACA,YAAA;EACA,UAAA;EACA,0CAAA;EACA,wFAAA;EACA,8BAAA;EACA,4BAAA;EACA,4BAAA;EACA,YAAA;AADpB;AAIgB;EACI,gBAAA;EACA,aAAA;EACA,wBAAA;AAFpB;AAKgB;EACI,WAAA;AAHpB;AAOY;EACI,kBAAA;EACA,gBAAA;EACA,yBAAA;AALhB;AAOgB;EACI,mDAAA;AALpB;AAQgB;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,SAAA;EACA,sBAAA;AANpB;AAQoB;EACI,6BAAA;EACA,YAAA;AANxB;AAUgB;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;EACA,kBAAA;EACA,SAAA;EACA,sBAAA;AARpB;AAWgB;EACI,YAAA;EACA,kBAAA;AATpB;AAUoB;EACI,kBAAA;EACA,UAAA;EACA,QAAA;AARxB;AASwB;EACI,eAAA;AAP5B;AAUwB;EACI,YAAA;EACA,WAAA;AAR5B;AAYoB;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;EACA,kBAAA;EACA,UAAA;EACA,QAAA;AAVxB;AAWwB;EACI,aAAA;AAT5B;AAYwB;EACI,uBAAA;EACA,mBAAA;EACA,mBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;AAV5B;AAawB;EACI,UAAA;AAX5B;AAcwB;EACI,sBAAA;EACA,yBAAA;AAZ5B;AAewB;EACI,uBAAA;EACA,mBAAA;EACA,yBAAA;EACA,YAAA;EACA,gBAAA;EACA,YAAA;AAb5B;AAgBwB;EACI,UAAA;AAd5B;AAiBwB;EACI,uBAAA;AAf5B;AAkBwB;EACI,mBAAA;EACA,YAAA;AAhB5B;AAqBgB;EACI,eAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AAnBpB;AAqBoB;EACI,WAAA;EACA,cAAA;AAnBxB;AAqBwB;EACI,aAAA;EACA,+BAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;AAnB5B;AAqB4B;EACI,kCAAA;EACA,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;AAnBhC;AAsB4B;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,wBAAA;AApBhC;AAsBgC;EACI,yBAAA;AApBpC;AAyBwB;EACI,iDAAA;AAvB5B",sourcesContent:[`#nmeNodeList {\r background: #333333;\r height: 100%;\r margin: 0;\r padding: 0;\r display: grid;\r width: 100%;\r overflow: hidden;\r \r .panes {\r overflow: hidden;\r \r .pane {\r color: white;\r \r overflow: hidden;\r height: 100%;\r \r -webkit-user-select: none;\r -moz-user-select: none;\r -ms-user-select: none;\r user-select: none;\r \r .filter {\r display: flex;\r align-items: stretch;\r \r input {\r width: 100%;\r margin: 10px 10px 5px 10px;\r display: block;\r border: none;\r padding: 0;\r border-bottom: solid 1px rgb(51, 122, 183);\r background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 96%, rgb(51, 122, 183) 4%);\r background-position: -1000px 0;\r background-size: 1000px 100%;\r background-repeat: no-repeat;\r color: white;\r }\r \r input:focus {\r box-shadow: none;\r outline: none;\r background-position: 0 0;\r }\r \r input::placeholder {\r color: gray;\r }\r }\r \r .list-container {\r overflow-x: hidden;\r overflow-y: auto;\r height: calc(100% - 32px);\r \r .underline {\r border-bottom: 0.5px solid rgba(255, 255, 255, 0.5);\r }\r \r .draggableLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r background: #222222;\r cursor: grab;\r text-align: center;\r margin: 0;\r box-sizing: border-box;\r \r &:hover {\r background: rgb(51, 122, 183);\r color: white;\r }\r }\r \r .nonDraggableLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r background: #222222;\r text-align: center;\r margin: 0;\r box-sizing: border-box;\r }\r \r .withButton {\r height: 30px;\r position: relative;\r .icon {\r position: absolute;\r right: 4px;\r top: 5px;\r &:hover {\r cursor: pointer;\r }\r \r .img {\r height: 17px;\r width: 17px;\r }\r }\r \r .buttonLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r padding-bottom: 5px;\r position: absolute;\r right: 0px;\r top: 2px;\r input[type="file"] {\r display: none;\r }\r \r .file-upload {\r background: transparent;\r border: transparent;\r padding: 15px 200px;\r opacity: 0.9;\r cursor: pointer;\r text-align: center;\r }\r \r .file-upload:hover {\r opacity: 1;\r }\r \r .file-upload:active {\r transform: scale(0.98);\r transform-origin: 0.5 0.5;\r }\r \r button {\r background: transparent;\r border: transparent;\r margin: 5px 10px 5px 10px;\r color: white;\r padding: 4px 5px;\r opacity: 0.9;\r }\r \r button:hover {\r opacity: 0;\r }\r \r button:active {\r background: transparent;\r }\r \r button:focus {\r border: transparent;\r outline: 0px;\r }\r }\r }\r \r .paneContainer {\r margin-top: 3px;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r \r .paneContainer-content {\r grid-row: 1;\r grid-column: 1;\r \r .header {\r display: grid;\r grid-template-columns: 1fr auto;\r background: #555555;\r height: 30px;\r padding-right: 5px;\r cursor: pointer;\r \r .title {\r border-left: 3px solid transparent;\r padding-left: 5px;\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .collapse {\r grid-column: 2;\r display: flex;\r align-items: center;\r justify-items: center;\r transform-origin: center;\r \r &.closed {\r transform: rotate(180deg);\r }\r }\r }\r \r .paneList > div:not(:last-child) {\r border-bottom: 1px solid rgba(255, 255, 255, 0.3);\r }\r }\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/components/propertyTab/propertyTab.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.nme-right-panel #propertyTab { color: white; background: #333333; } .nme-right-panel #propertyTab #header { height: 30px; font-size: 16px; color: white; background: #222222; grid-row: 1; text-align: center; display: grid; grid-template-columns: 30px 1fr; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .nme-right-panel #propertyTab #header #logo { position: relative; grid-column: 1; width: 24px; height: 24px; left: 0; display: flex; align-self: center; justify-self: center; } .nme-right-panel #propertyTab #header #title { grid-column: 2; display: grid; align-items: center; text-align: center; } .nme-right-panel #propertyTab .range { -webkit-appearance: none; width: 120px; height: 6px; background: #d3d3d3; border-radius: 5px; outline: none; opacity: 0.7; -webkit-transition: 0.2s; transition: opacity 0.2s; } .nme-right-panel #propertyTab .range:hover { opacity: 1; } .nme-right-panel #propertyTab .range::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 14px; height: 14px; border-radius: 50%; background: rgb(51, 122, 183); cursor: pointer; } .nme-right-panel #propertyTab .range::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: rgb(51, 122, 183); cursor: pointer; } .nme-right-panel #propertyTab input[type=color] { -webkit-appearance: none; border: 1px solid rgba(255, 255, 255, 0.5); padding: 0; width: 30px; height: 20px; } .nme-right-panel #propertyTab input[type=color]::-webkit-color-swatch-wrapper { padding: 0; } .nme-right-panel #propertyTab input[type=color]::-webkit-color-swatch { border: none; } .nme-right-panel #propertyTab .sliderLine { padding-left: 5px; height: 30px; display: grid; grid-template-rows: 100%; grid-template-columns: 1fr 50px auto; } .nme-right-panel #propertyTab .sliderLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .slider { grid-column: 3; grid-row: 1; margin-right: 5px; width: 90%; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .floatLine { grid-column: 2; padding-left: 5px; } .nme-right-panel #propertyTab .sliderLine .floatLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .floatLine .short { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .sliderLine .floatLine .short input { width: 35px; } .nme-right-panel #propertyTab .sliderLine .floatLine .short input::-webkit-outer-spin-button, .nme-right-panel #propertyTab .sliderLine .floatLine .short input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .nme-right-panel #propertyTab .sliderLine .floatLine .short input[type=number] { -moz-appearance: textfield; } .nme-right-panel #propertyTab .sliderLine .floatLine .copy { display: none; } .nme-right-panel #propertyTab .sliderLine .copy { display: none; } .nme-right-panel #propertyTab .textInputLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr 120px auto; } .nme-right-panel #propertyTab .textInputLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .textInputLine .value { display: flex; align-items: center; grid-column: 2; } .nme-right-panel #propertyTab .textInputLine .value input { width: calc(100% - 5px); margin-right: 5px; } .nme-right-panel #propertyTab .textInputArea { padding-left: 5px; height: 50px; display: grid; grid-template-columns: 1fr 120px; } .nme-right-panel #propertyTab .textInputArea .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .textInputArea textarea { margin-right: 5px; margin-left: -50%; height: 40px; resize: none; } .nme-right-panel #propertyTab .textInputArea .value { display: flex; align-items: center; grid-column: 2; } .nme-right-panel #propertyTab .paneContainer { margin-top: 3px; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; } .nme-right-panel #propertyTab .paneContainer .paneList { border-left: 3px solid transparent; } .nme-right-panel #propertyTab .paneContainer:hover .paneList { border-left: 3px solid rgba(51, 122, 183, 0.8); } .nme-right-panel #propertyTab .paneContainer:hover .paneContainer-content .header .title { border-left: 3px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .paneContainer .paneContainer-highlight-border { grid-row: 1; grid-column: 1; opacity: 1; border: 3px solid red; transition: opacity 250ms; pointer-events: none; } .nme-right-panel #propertyTab .paneContainer .paneContainer-highlight-border.transparent { opacity: 0; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content { grid-row: 1; grid-column: 1; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header { display: grid; grid-template-columns: 1fr auto; background: #555555; height: 30px; padding-right: 5px; cursor: pointer; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header .title { border-left: 3px solid transparent; padding-left: 5px; grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header .collapse { grid-column: 2; display: flex; align-items: center; justify-items: center; transform-origin: center; } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .header .collapse.closed { transform: rotate(180deg); } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .paneList > div:not(:last-child) { border-bottom: 0.5px solid rgba(255, 255, 255, 0.1); } .nme-right-panel #propertyTab .paneContainer .paneContainer-content .fragment > div:not(:last-child) { border-bottom: 0.5px solid rgba(255, 255, 255, 0.1); } .nme-right-panel #propertyTab .color-picker { height: calc(100% - 8px); margin: 4px; width: calc(100% - 8px); } .nme-right-panel #propertyTab .color-picker .color-rect { height: calc(100% - 4px); border: 2px white solid; cursor: pointer; min-height: 18px; } .nme-right-panel #propertyTab .color-picker .color-picker-cover { position: fixed; top: 0px; right: 0px; bottom: 0px; left: 0px; z-index: 1; } .nme-right-panel #propertyTab .color-picker .color-picker-float { z-index: 2; position: absolute; } .nme-right-panel #propertyTab .gradient-step { display: grid; grid-template-rows: 100%; grid-template-columns: 20px 30px 40px auto 20px 30px; padding-top: 5px; padding-left: 5px; padding-bottom: 5px; } .nme-right-panel #propertyTab .gradient-step .step { grid-row: 1; grid-column: 1; } .nme-right-panel #propertyTab .gradient-step .color { grid-row: 1; grid-column: 2; cursor: pointer; } .nme-right-panel #propertyTab .gradient-step .step-value { margin-left: 5px; grid-row: 1; grid-column: 3; text-align: right; margin-right: 5px; } .nme-right-panel #propertyTab .gradient-step .step-slider { grid-row: 1; grid-column: 4; display: grid; justify-content: stretch; align-content: center; margin-right: -5px; padding-left: 12px; } .nme-right-panel #propertyTab .gradient-step .step-slider input { width: 90%; } .nme-right-panel #propertyTab .gradient-step .gradient-copy { grid-row: 1; grid-column: 5; display: grid; align-content: center; justify-content: center; } .nme-right-panel #propertyTab .gradient-step .gradient-copy .img { height: 20px; width: 20px; } .nme-right-panel #propertyTab .gradient-step .gradient-copy .img:hover { cursor: pointer; } .nme-right-panel #propertyTab .gradient-step .gradient-delete { grid-row: 1; grid-column: 6; display: grid; align-content: center; justify-content: center; } .nme-right-panel #propertyTab .gradient-step .gradient-delete .img { height: 20px; width: 20px; } .nme-right-panel #propertyTab .gradient-step .gradient-delete .img:hover { cursor: pointer; } .nme-right-panel #propertyTab .floatLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr 120px; } .nme-right-panel #propertyTab .floatLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .floatLine .value { grid-column: 2; display: flex; align-items: center; } .nme-right-panel #propertyTab .floatLine .value input { width: 110px; } .nme-right-panel #propertyTab .floatLine .short { grid-column: 2; display: flex; align-items: center; } .nme-right-panel #propertyTab .floatLine .short input { width: 27px; } .nme-right-panel #propertyTab .floatLine .short input::-webkit-outer-spin-button, .nme-right-panel #propertyTab .floatLine .short input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .nme-right-panel #propertyTab .floatLine .short input[type=number] { -moz-appearance: textfield; } .nme-right-panel #propertyTab .floatLine .copy { display: none; } .nme-right-panel #propertyTab .vector3Line { padding-left: 5px; display: grid; } .nme-right-panel #propertyTab .vector3Line .firstLine { display: grid; grid-template-columns: 1fr auto 20px; height: 30px; } .nme-right-panel #propertyTab .vector3Line .firstLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .vector3Line .firstLine .vector { grid-column: 2; display: flex; align-items: center; text-align: right; opacity: 0.8; } .nme-right-panel #propertyTab .vector3Line .firstLine .expand { grid-column: 3; display: grid; align-items: center; justify-items: center; cursor: pointer; } .nme-right-panel #propertyTab .vector3Line .firstLine .copy { display: none; } .nme-right-panel #propertyTab .vector3Line .secondLine { display: grid; padding-right: 5px; border-left: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .vector3Line .secondLine .no-right-margin { margin-right: 0; } .nme-right-panel #propertyTab .vector3Line .secondLine .numeric { display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .vector3Line .secondLine .numeric-label { text-align: right; grid-column: 1; display: flex; align-items: center; justify-self: right; margin-right: 10px; } .nme-right-panel #propertyTab .vector3Line .secondLine .numeric-value { width: 120px; grid-column: 2; display: flex; align-items: center; border: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .buttonLine { height: 30px; display: grid; align-items: center; justify-items: stretch; padding-bottom: 5px; } .nme-right-panel #propertyTab .buttonLine.disabled { opacity: 0.3; } .nme-right-panel #propertyTab .buttonLine input[type=file] { display: none; } .nme-right-panel #propertyTab .buttonLine .file-upload { background: #222222; border: 1px solid rgb(51, 122, 183); margin: 5px 10px; color: white; padding: 4px 5px; padding-top: 0px; opacity: 0.9; cursor: pointer; text-align: center; } .nme-right-panel #propertyTab .buttonLine .file-upload:hover { opacity: 1; } .nme-right-panel #propertyTab .buttonLine .file-upload:active { transform: scale(0.98); transform-origin: 0.5 0.5; } .nme-right-panel #propertyTab .buttonLine button { background: #222222; border: 1px solid rgb(51, 122, 183); margin: 5px 10px 5px 10px; color: white; padding: 4px 5px; opacity: 0.9; } .nme-right-panel #propertyTab .buttonLine button:hover { opacity: 1; } .nme-right-panel #propertyTab .buttonLine button:active { background: #282828; } .nme-right-panel #propertyTab .buttonLine button:focus { border: 1px solid rgb(51, 122, 183); outline: 0px; } .nme-right-panel #propertyTab .checkBoxLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .checkBoxLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .checkBoxLine .checkBox { grid-column: 2; display: flex; align-items: center; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .lbl { position: relative; display: block; height: 14px; width: 34px; margin-right: 5px; background: #898989; border-radius: 100px; cursor: pointer; transition: all 0.3s ease; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .lbl:after { position: absolute; left: 3px; top: 2px; display: block; width: 10px; height: 10px; border-radius: 100px; background: #fff; box-shadow: 0px 3px 3px rgba(0, 0, 0, 0.05); content: ""; transition: all 0.15s ease; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .lbl:active:after { transform: scale(1.15, 0.85); } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label { background: rgb(51, 122, 183); } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label:after { left: 20px; background: rgb(22, 73, 117); } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label.disabled { background: rgb(22, 73, 117); cursor: pointer; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx:checked ~ label.disabled:after { left: 20px; background: rgb(85, 85, 85); cursor: pointer; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .cbx ~ label.disabled { background: rgb(85, 85, 85); cursor: pointer; } .nme-right-panel #propertyTab .checkBoxLine .checkBox .hidden { display: none; } .nme-right-panel #propertyTab .checkBoxLine .copy { display: none; } .nme-right-panel #propertyTab .listLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .listLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .listLine .options { grid-column: 2; display: flex; align-items: center; margin-right: 5px; } .nme-right-panel #propertyTab .listLine .options select { width: 115px; } .nme-right-panel #propertyTab .listLine .copy { display: none; } .nme-right-panel #propertyTab .color3Line { padding-left: 5px; display: grid; } .nme-right-panel #propertyTab .color3Line .firstLine { height: 30px; display: grid; grid-template-columns: 1fr auto 20px; } .nme-right-panel #propertyTab .color3Line .firstLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .color3Line .firstLine .textInputLine { display: none; } .nme-right-panel #propertyTab .color3Line .firstLine .color3 { grid-column: 2; width: 50px; display: flex; align-items: center; } .nme-right-panel #propertyTab .color3Line .firstLine .color3 input { margin-right: 5px; } .nme-right-panel #propertyTab .color3Line .firstLine .expand { grid-column: 3; display: grid; align-items: center; justify-items: center; cursor: pointer; } .nme-right-panel #propertyTab .color3Line .firstLine .copy { grid-column: 4; display: grid; align-items: center; justify-items: center; cursor: pointer; } .nme-right-panel #propertyTab .color3Line .firstLine .copy img { height: 100%; } .nme-right-panel #propertyTab .color3Line .secondLine { display: grid; padding-right: 5px; border-left: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .color3Line .secondLine .numeric { display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .color3Line .secondLine .numeric-label { text-align: right; grid-column: 1; display: flex; align-items: center; justify-self: right; margin-right: 10px; } .nme-right-panel #propertyTab .color3Line .secondLine .numeric-value { width: 120px; grid-column: 2; display: flex; align-items: center; border: 1px solid rgb(51, 122, 183); } .nme-right-panel #propertyTab .textLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } .nme-right-panel #propertyTab .textLine .label { grid-column: 1; display: flex; align-items: center; } .nme-right-panel #propertyTab .textLine .link-value { grid-column: 2; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; text-align: end; opacity: 0.8; margin: 5px; margin-top: 6px; max-width: 140px; text-decoration: underline; cursor: pointer; } .nme-right-panel #propertyTab .textLine .value { grid-column: 2; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; text-align: end; opacity: 0.8; margin: 5px; margin-top: 6px; max-width: 200px; -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; } .nme-right-panel #propertyTab .textLine .value.check { color: green; } .nme-right-panel #propertyTab .textLine .value.uncheck { color: red; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/components/propertyTab/propertyTab.scss"],names:[],mappings:"AACI;EAEI,YAAA;EACA,mBAAA;AADR;AAGQ;EACI,YAAA;EACA,eAAA;EACA,YAAA;EACA,mBAAA;EACA,WAAA;EACA,kBAAA;EACA,aAAA;EACA,+BAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AADZ;AAGY;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,OAAA;EACA,aAAA;EACA,kBAAA;EACA,oBAAA;AADhB;AAIY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,kBAAA;AAFhB;AAMQ;EACI,wBAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,kBAAA;EACA,aAAA;EACA,YAAA;EACA,wBAAA;EACA,wBAAA;AAJZ;AAOQ;EACI,UAAA;AALZ;AAQQ;EACI,wBAAA;EACA,gBAAA;EACA,WAAA;EACA,YAAA;EACA,kBAAA;EACA,6BAAA;EACA,eAAA;AANZ;AASQ;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,6BAAA;EACA,eAAA;AAPZ;AAUQ;EACI,wBAAA;EACA,0CAAA;EACA,UAAA;EACA,WAAA;EACA,YAAA;AARZ;AAUQ;EACI,UAAA;AARZ;AAUQ;EACI,YAAA;AARZ;AAWQ;EACI,iBAtFgB;EAuFhB,YAAA;EACA,aAAA;EACA,wBAAA;EACA,oCAAA;AATZ;AAWY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAThB;AAYY;EACI,cAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,aAAA;EACA,mBAAA;AAVhB;AAaY;EACI,cAAA;EACA,iBA7GY;AAkG5B;AAagB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAXpB;AAcgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAZpB;AAcoB;EACI,WAAA;AAZxB;AAeoB;;EAEI,wBAAA;EACA,SAAA;AAbxB;AAgBoB;EACI,0BAAA;AAdxB;AAkBgB;EACI,aAAA;AAhBpB;AAoBY;EACI,aAAA;AAlBhB;AAsBQ;EACI,iBApJgB;EAqJhB,YAAA;EACA,aAAA;EACA,qCAAA;AApBZ;AAsBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AApBhB;AAuBY;EACI,aAAA;EACA,mBAAA;EACA,cAAA;AArBhB;AAuBgB;EACI,uBAAA;EACA,iBAAA;AArBpB;AA0BQ;EACI,iBA5KgB;EA6KhB,YAAA;EACA,aAAA;EACA,gCAAA;AAxBZ;AA0BY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAxBhB;AA2BY;EACI,iBAAA;EACA,iBAAA;EACA,YAAA;EACA,YAAA;AAzBhB;AA4BY;EACI,aAAA;EACA,mBAAA;EACA,cAAA;AA1BhB;AA8BQ;EACI,eAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AA5BZ;AA8BY;EACI,kCAAA;AA5BhB;AAgCgB;EACI,8CAAA;AA9BpB;AAmCwB;EACI,wCAAA;AAjC5B;AAuCY;EACI,WAAA;EACA,cAAA;EACA,UAAA;EACA,qBAAA;EACA,yBAAA;EACA,oBAAA;AArChB;AAuCgB;EACI,UAAA;AArCpB;AAyCY;EACI,WAAA;EACA,cAAA;AAvChB;AAyCgB;EACI,aAAA;EACA,+BAAA;EACA,mBAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;AAvCpB;AAyCoB;EACI,kCAAA;EACA,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;AAvCxB;AA0CoB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,wBAAA;AAxCxB;AA0CwB;EACI,yBAAA;AAxC5B;AA6CgB;EACI,mDAAA;AA3CpB;AA8CgB;EACI,mDAAA;AA5CpB;AAiDQ;EACI,wBAAA;EACA,WAAA;EACA,uBAAA;AA/CZ;AAiDY;EACI,wBAAA;EACA,uBAAA;EACA,eAAA;EACA,gBAAA;AA/ChB;AAkDY;EACI,eAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,SAAA;EACA,UAAA;AAhDhB;AAmDY;EACI,UAAA;EACA,kBAAA;AAjDhB;AAqDQ;EACI,aAAA;EACA,wBAAA;EACA,oDAAA;EACA,gBAAA;EACA,iBAAA;EACA,mBAAA;AAnDZ;AAqDY;EACI,WAAA;EACA,cAAA;AAnDhB;AAsDY;EACI,WAAA;EACA,cAAA;EACA,eAAA;AApDhB;AAuDY;EACI,gBAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,iBAAA;AArDhB;AAwDY;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,qBAAA;EACA,kBAAA;EACA,kBAAA;AAtDhB;AAwDgB;EACI,UAAA;AAtDpB;AA0DY;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AAxDhB;AA0DgB;EACI,YAAA;EACA,WAAA;AAxDpB;AA0DgB;EACI,eAAA;AAxDpB;AA2DY;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,uBAAA;AAzDhB;AA0DgB;EACI,YAAA;EACA,WAAA;AAxDpB;AA0DgB;EACI,eAAA;AAxDpB;AA6DQ;EACI,iBAzXgB;EA0XhB,YAAA;EACA,aAAA;EACA,gCAAA;AA3DZ;AA6DY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA3DhB;AA8DY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AA7DhB;AA+DgB;EACI,YAAA;AA7DpB;AAiEY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AAhEhB;AAkEgB;EACI,WAAA;AAhEpB;AAmEgB;;EAEI,wBAAA;EACA,SAAA;AAjEpB;AAoEgB;EACI,0BAAA;AAlEpB;AAsEY;EACI,aAAA;AApEhB;AAwEQ;EACI,iBA1agB;EA2ahB,aAAA;AAtEZ;AAwEY;EACI,aAAA;EACA,oCAAA;EACA,YAAA;AAtEhB;AAwEgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAtEpB;AAyEgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,iBAAA;EACA,YAAA;AAvEpB;AA0EgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AAxEpB;AA2EgB;EACI,aAAA;AAzEpB;AA6EY;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AA3EhB;AA6EgB;EACI,eAAA;AA3EpB;AA8EgB;EACI,aAAA;EACA,+BAAA;AA5EpB;AA+EgB;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AA7EpB;AAgFgB;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AA9EpB;AAmFQ;EACI,YAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,mBAAA;AAjFZ;AAmFY;EACI,YAAA;AAjFhB;AAoFY;EACI,aAAA;AAlFhB;AAqFY;EACI,mBAAA;EACA,mCAAA;EACA,gBAAA;EACA,YAAA;EACA,gBAAA;EACA,gBAAA;EACA,YAAA;EACA,eAAA;EACA,kBAAA;AAnFhB;AAsFY;EACI,UAAA;AApFhB;AAuFY;EACI,sBAAA;EACA,yBAAA;AArFhB;AAwFY;EACI,mBAAA;EACA,mCAAA;EACA,yBAAA;EACA,YAAA;EACA,gBAAA;EACA,YAAA;AAtFhB;AAyFY;EACI,UAAA;AAvFhB;AA0FY;EACI,mBAAA;AAxFhB;AA2FY;EACI,mCAAA;EACA,YAAA;AAzFhB;AA6FQ;EACI,iBA1iBgB;EA2iBhB,YAAA;EACA,aAAA;EACA,+BAAA;AA3FZ;AA6FY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA3FhB;AA8FY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;AA7FhB;AA+FgB;EACI,kBAAA;EACA,cAAA;EACA,YAAA;EACA,WAAA;EACA,iBAAA;EACA,mBAAA;EACA,oBAAA;EACA,eAAA;EACA,yBAAA;AA7FpB;AAgGgB;EACI,kBAAA;EACA,SAAA;EACA,QAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,oBAAA;EACA,gBAAA;EACA,2CAAA;EACA,WAAA;EACA,0BAAA;AA9FpB;AAiGgB;EACI,4BAAA;AA/FpB;AAkGgB;EACI,6BAAA;AAhGpB;AAmGgB;EACI,UAAA;EACA,4BAAA;AAjGpB;AAoGgB;EACI,4BAAA;EACA,eAAA;AAlGpB;AAqGgB;EACI,UAAA;EACA,2BAAA;EACA,eAAA;AAnGpB;AAsGgB;EACI,2BAAA;EACA,eAAA;AApGpB;AAuGgB;EACI,aAAA;AArGpB;AAyGY;EACI,aAAA;AAvGhB;AA2GQ;EACI,iBA7nBgB;EA8nBhB,YAAA;EACA,aAAA;EACA,+BAAA;AAzGZ;AA2GY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AAzGhB;AA4GY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;EACA,iBAAA;AA3GhB;AA6GgB;EACI,YAAA;AA3GpB;AA+GY;EACI,aAAA;AA7GhB;AAiHQ;EACI,iBA1pBgB;EA2pBhB,aAAA;AA/GZ;AAiHY;EACI,YAAA;EACA,aAAA;EACA,oCAAA;AA/GhB;AAiHgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA/GpB;AAkHgB;EACI,aAAA;AAhHpB;AAmHgB;EACI,cAAA;EACA,WAAA;EAEA,aAAA;EACA,mBAAA;AAlHpB;AAoHoB;EACI,iBAAA;AAlHxB;AAsHgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AApHpB;AAuHgB;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,qBAAA;EACA,eAAA;AArHpB;AAsHoB;EACI,YAAA;AApHxB;AAyHY;EACI,aAAA;EACA,kBAAA;EACA,wCAAA;AAvHhB;AAyHgB;EACI,aAAA;EACA,+BAAA;AAvHpB;AA0HgB;EACI,iBAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mBAAA;EACA,kBAAA;AAxHpB;AA2HgB;EACI,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,mCAAA;AAzHpB;AA8HQ;EACI,iBA1uBgB;EA2uBhB,YAAA;EACA,aAAA;EACA,+BAAA;AA5HZ;AA8HY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;AA5HhB;AA+HY;EACI,cAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,0BAAA;EACA,eAAA;AA7HhB;AAgIY;EACI,cAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;EACA,gBAAA;EACA,yBAAA;EACA,sBAAA;EACA,qBAAA;EACA,iBAAA;AA9HhB;AAgIgB;EACI,YAAA;AA9HpB;AAiIgB;EACI,UAAA;AA/HpB",sourcesContent:[`.nme-right-panel {\r #propertyTab {\r $line-padding-left: 5px;\r color: white;\r background: #333333;\r \r #header {\r height: 30px;\r font-size: 16px;\r color: white;\r background: #222222;\r grid-row: 1;\r text-align: center;\r display: grid;\r grid-template-columns: 30px 1fr;\r -webkit-user-select: none;\r -moz-user-select: none;\r -ms-user-select: none;\r user-select: none;\r \r #logo {\r position: relative;\r grid-column: 1;\r width: 24px;\r height: 24px;\r left: 0;\r display: flex;\r align-self: center;\r justify-self: center;\r }\r \r #title {\r grid-column: 2;\r display: grid;\r align-items: center;\r text-align: center;\r }\r }\r \r .range {\r -webkit-appearance: none;\r width: 120px;\r height: 6px;\r background: #d3d3d3;\r border-radius: 5px;\r outline: none;\r opacity: 0.7;\r -webkit-transition: 0.2s;\r transition: opacity 0.2s;\r }\r \r .range:hover {\r opacity: 1;\r }\r \r .range::-webkit-slider-thumb {\r -webkit-appearance: none;\r appearance: none;\r width: 14px;\r height: 14px;\r border-radius: 50%;\r background: rgb(51, 122, 183);\r cursor: pointer;\r }\r \r .range::-moz-range-thumb {\r width: 14px;\r height: 14px;\r border-radius: 50%;\r background: rgb(51, 122, 183);\r cursor: pointer;\r }\r \r input[type="color"] {\r -webkit-appearance: none;\r border: 1px solid rgba(255, 255, 255, 0.5);\r padding: 0;\r width: 30px;\r height: 20px;\r }\r input[type="color"]::-webkit-color-swatch-wrapper {\r padding: 0;\r }\r input[type="color"]::-webkit-color-swatch {\r border: none;\r }\r \r .sliderLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 1fr 50px auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .slider {\r grid-column: 3;\r grid-row: 1;\r margin-right: 5px;\r width: 90%;\r display: flex;\r align-items: center;\r }\r \r .floatLine {\r grid-column: 2;\r padding-left: $line-padding-left;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .short {\r grid-column: 1;\r display: flex;\r align-items: center;\r \r input {\r width: 35px;\r }\r \r input::-webkit-outer-spin-button,\r input::-webkit-inner-spin-button {\r -webkit-appearance: none;\r margin: 0;\r }\r \r input[type="number"] {\r -moz-appearance: textfield;\r }\r }\r \r .copy {\r display: none;\r }\r }\r \r .copy {\r display: none;\r }\r }\r \r .textInputLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr 120px auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .value {\r display: flex;\r align-items: center;\r grid-column: 2;\r \r input {\r width: calc(100% - 5px);\r margin-right: 5px;\r }\r }\r }\r \r .textInputArea {\r padding-left: $line-padding-left;\r height: 50px;\r display: grid;\r grid-template-columns: 1fr 120px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r textarea {\r margin-right: 5px;\r margin-left: -50%;\r height: 40px;\r resize: none;\r }\r \r .value {\r display: flex;\r align-items: center;\r grid-column: 2;\r }\r }\r \r .paneContainer {\r margin-top: 3px;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r \r .paneList {\r border-left: 3px solid transparent;\r }\r \r &:hover {\r .paneList {\r border-left: 3px solid rgba(51, 122, 183, 0.8);\r }\r \r .paneContainer-content {\r .header {\r .title {\r border-left: 3px solid rgb(51, 122, 183);\r }\r }\r }\r }\r \r .paneContainer-highlight-border {\r grid-row: 1;\r grid-column: 1;\r opacity: 1;\r border: 3px solid red;\r transition: opacity 250ms;\r pointer-events: none;\r \r &.transparent {\r opacity: 0;\r }\r }\r \r .paneContainer-content {\r grid-row: 1;\r grid-column: 1;\r \r .header {\r display: grid;\r grid-template-columns: 1fr auto;\r background: #555555;\r height: 30px;\r padding-right: 5px;\r cursor: pointer;\r \r .title {\r border-left: 3px solid transparent;\r padding-left: 5px;\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .collapse {\r grid-column: 2;\r display: flex;\r align-items: center;\r justify-items: center;\r transform-origin: center;\r \r &.closed {\r transform: rotate(180deg);\r }\r }\r }\r \r .paneList > div:not(:last-child) {\r border-bottom: 0.5px solid rgba(255, 255, 255, 0.1);\r }\r \r .fragment > div:not(:last-child) {\r border-bottom: 0.5px solid rgba(255, 255, 255, 0.1);\r }\r }\r }\r \r .color-picker {\r height: calc(100% - 8px);\r margin: 4px;\r width: calc(100% - 8px);\r \r .color-rect {\r height: calc(100% - 4px);\r border: 2px white solid;\r cursor: pointer;\r min-height: 18px;\r }\r \r .color-picker-cover {\r position: fixed;\r top: 0px;\r right: 0px;\r bottom: 0px;\r left: 0px;\r z-index: 1;\r }\r \r .color-picker-float {\r z-index: 2;\r position: absolute;\r }\r }\r \r .gradient-step {\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 20px 30px 40px auto 20px 30px;\r padding-top: 5px;\r padding-left: 5px;\r padding-bottom: 5px;\r \r .step {\r grid-row: 1;\r grid-column: 1;\r }\r \r .color {\r grid-row: 1;\r grid-column: 2;\r cursor: pointer;\r }\r \r .step-value {\r margin-left: 5px;\r grid-row: 1;\r grid-column: 3;\r text-align: right;\r margin-right: 5px;\r }\r \r .step-slider {\r grid-row: 1;\r grid-column: 4;\r display: grid;\r justify-content: stretch;\r align-content: center;\r margin-right: -5px;\r padding-left: 12px;\r \r input {\r width: 90%;\r }\r }\r \r .gradient-copy {\r grid-row: 1;\r grid-column: 5;\r display: grid;\r align-content: center;\r justify-content: center;\r \r .img {\r height: 20px;\r width: 20px;\r }\r .img:hover {\r cursor: pointer;\r }\r }\r .gradient-delete {\r grid-row: 1;\r grid-column: 6;\r display: grid;\r align-content: center;\r justify-content: center;\r .img {\r height: 20px;\r width: 20px;\r }\r .img:hover {\r cursor: pointer;\r }\r }\r }\r \r .floatLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr 120px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .value {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r \r input {\r width: 110px;\r }\r }\r \r .short {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r \r input {\r width: 27px;\r }\r \r input::-webkit-outer-spin-button,\r input::-webkit-inner-spin-button {\r -webkit-appearance: none;\r margin: 0;\r }\r \r input[type="number"] {\r -moz-appearance: textfield;\r }\r }\r \r .copy {\r display: none;\r }\r }\r \r .vector3Line {\r padding-left: $line-padding-left;\r display: grid;\r \r .firstLine {\r display: grid;\r grid-template-columns: 1fr auto 20px;\r height: 30px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .vector {\r grid-column: 2;\r display: flex;\r align-items: center;\r text-align: right;\r opacity: 0.8;\r }\r \r .expand {\r grid-column: 3;\r display: grid;\r align-items: center;\r justify-items: center;\r cursor: pointer;\r }\r \r .copy {\r display: none;\r }\r }\r \r .secondLine {\r display: grid;\r padding-right: 5px;\r border-left: 1px solid rgb(51, 122, 183);\r \r .no-right-margin {\r margin-right: 0;\r }\r \r .numeric {\r display: grid;\r grid-template-columns: 1fr auto;\r }\r \r .numeric-label {\r text-align: right;\r grid-column: 1;\r display: flex;\r align-items: center;\r justify-self: right;\r margin-right: 10px;\r }\r \r .numeric-value {\r width: 120px;\r grid-column: 2;\r display: flex;\r align-items: center;\r border: 1px solid rgb(51, 122, 183);\r }\r }\r }\r \r .buttonLine {\r height: 30px;\r display: grid;\r align-items: center;\r justify-items: stretch;\r padding-bottom: 5px;\r \r &.disabled {\r opacity: 0.3;\r }\r \r input[type="file"] {\r display: none;\r }\r \r .file-upload {\r background: #222222;\r border: 1px solid rgb(51, 122, 183);\r margin: 5px 10px;\r color: white;\r padding: 4px 5px;\r padding-top: 0px;\r opacity: 0.9;\r cursor: pointer;\r text-align: center;\r }\r \r .file-upload:hover {\r opacity: 1;\r }\r \r .file-upload:active {\r transform: scale(0.98);\r transform-origin: 0.5 0.5;\r }\r \r button {\r background: #222222;\r border: 1px solid rgb(51, 122, 183);\r margin: 5px 10px 5px 10px;\r color: white;\r padding: 4px 5px;\r opacity: 0.9;\r }\r \r button:hover {\r opacity: 1;\r }\r \r button:active {\r background: #282828;\r }\r \r button:focus {\r border: 1px solid rgb(51, 122, 183);\r outline: 0px;\r }\r }\r \r .checkBoxLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .checkBox {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r \r .lbl {\r position: relative;\r display: block;\r height: 14px;\r width: 34px;\r margin-right: 5px;\r background: #898989;\r border-radius: 100px;\r cursor: pointer;\r transition: all 0.3s ease;\r }\r \r .lbl:after {\r position: absolute;\r left: 3px;\r top: 2px;\r display: block;\r width: 10px;\r height: 10px;\r border-radius: 100px;\r background: #fff;\r box-shadow: 0px 3px 3px rgba(0, 0, 0, 0.05);\r content: "";\r transition: all 0.15s ease;\r }\r \r .lbl:active:after {\r transform: scale(1.15, 0.85);\r }\r \r .cbx:checked ~ label {\r background: rgb(51, 122, 183);\r }\r \r .cbx:checked ~ label:after {\r left: 20px;\r background: rgb(22, 73, 117);\r }\r \r .cbx:checked ~ label.disabled {\r background: rgb(22, 73, 117);\r cursor: pointer;\r }\r \r .cbx:checked ~ label.disabled:after {\r left: 20px;\r background: rgb(85, 85, 85);\r cursor: pointer;\r }\r \r .cbx ~ label.disabled {\r background: rgb(85, 85, 85);\r cursor: pointer;\r }\r \r .hidden {\r display: none;\r }\r }\r \r .copy {\r display: none;\r }\r }\r \r .listLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .options {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r margin-right: 5px;\r \r select {\r width: 115px;\r }\r }\r \r .copy {\r display: none;\r }\r }\r \r .color3Line {\r padding-left: $line-padding-left;\r display: grid;\r \r .firstLine {\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto 20px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .textInputLine {\r display: none;\r }\r \r .color3 {\r grid-column: 2;\r width: 50px;\r \r display: flex;\r align-items: center;\r \r input {\r margin-right: 5px;\r }\r }\r \r .expand {\r grid-column: 3;\r display: grid;\r align-items: center;\r justify-items: center;\r cursor: pointer;\r }\r \r .copy {\r grid-column: 4;\r display: grid;\r align-items: center;\r justify-items: center;\r cursor: pointer;\r img {\r height: 100%;\r }\r }\r }\r \r .secondLine {\r display: grid;\r padding-right: 5px;\r border-left: 1px solid rgb(51, 122, 183);\r \r .numeric {\r display: grid;\r grid-template-columns: 1fr auto;\r }\r \r .numeric-label {\r text-align: right;\r grid-column: 1;\r display: flex;\r align-items: center;\r justify-self: right;\r margin-right: 10px;\r }\r \r .numeric-value {\r width: 120px;\r grid-column: 2;\r display: flex;\r align-items: center;\r border: 1px solid rgb(51, 122, 183);\r }\r }\r }\r \r .textLine {\r padding-left: $line-padding-left;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r }\r \r .link-value {\r grid-column: 2;\r white-space: nowrap;\r text-overflow: ellipsis;\r overflow: hidden;\r text-align: end;\r opacity: 0.8;\r margin: 5px;\r margin-top: 6px;\r max-width: 140px;\r text-decoration: underline;\r cursor: pointer;\r }\r \r .value {\r grid-column: 2;\r white-space: nowrap;\r text-overflow: ellipsis;\r overflow: hidden;\r text-align: end;\r opacity: 0.8;\r margin: 5px;\r margin-top: 6px;\r max-width: 200px;\r -webkit-user-select: text;\r -moz-user-select: text;\r -ms-user-select: text;\r user-select: text;\r \r &.check {\r color: green;\r }\r \r &.uncheck {\r color: red;\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!../../../tools/nodeEditor/dist/main.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`#node-editor-graph-root { display: grid; grid-template-rows: calc(100% - 120px) 120px; height: 100%; width: 100%; background: #464646; font: 14px "acumin-pro"; } #node-editor-graph-root.popup { grid-template-columns: 100%; overflow: hidden; } #node-editor-graph-root .wait-screen { display: grid; justify-content: center; align-content: center; height: 100%; width: 100%; background: #464646; opacity: 0.95; color: white; font: 24px "acumin-pro"; position: absolute; top: 0; left: 0; } #node-editor-graph-root .wait-screen.hidden { visibility: hidden; } #node-editor-graph-root #nmeNodeList { grid-row: 1/span 2; grid-column: 1; } #node-editor-graph-root #leftGrab { grid-row: 1/span 2; grid-column: 2; cursor: ew-resize; } #node-editor-graph-root #rightGrab { grid-row: 1/span 2; grid-column: 4; cursor: ew-resize; } #node-editor-graph-root .diagram-container { grid-row: 1; grid-column: 3; background: #5f5b60; width: 100%; height: 100%; } #node-editor-graph-root .diagram-container .diagram { display: none; width: 100%; height: 100%; } #node-editor-graph-root .nme-right-panel { grid-row: 1/span 2; grid-column: 5; display: grid; grid-template-rows: 1fr 40px auto 40px; grid-template-columns: 100%; height: 100%; overflow-y: auto; } #node-editor-graph-root #propertyTab { grid-row: 1; grid-column: 1; } #node-editor-graph-root .button { display: grid; justify-content: center; align-content: center; height: auto; width: 14.2857142857%; cursor: pointer; } #node-editor-graph-root .button:hover { background: rgb(51, 122, 183); color: white; opacity: 0.8; } #node-editor-graph-root .button.selected { background: rgb(51, 122, 183); color: white; } #node-editor-graph-root .button.align { justify-content: stretch; text-align: center; } #node-editor-graph-root #preview-mesh-bar { grid-row: 2; grid-column: 1; display: grid; grid-template-columns: auto 1fr 40px 40px 40px; align-items: center; font-size: 18px; background-color: #555555; } #node-editor-graph-root #preview-mesh-bar #file-picker { display: none; } #node-editor-graph-root #preview-mesh-bar .listLine { grid-column: 1; height: 40px; display: grid; grid-template-columns: 0px 1fr 0px; } #node-editor-graph-root #preview-mesh-bar .listLine .label { grid-column: 1; display: flex; align-items: center; font-size: 14px; } #node-editor-graph-root #preview-mesh-bar .listLine .options { grid-column: 2; display: flex; align-items: center; margin-left: 5px; } #node-editor-graph-root #preview-mesh-bar .listLine .options select { width: 115px; } #node-editor-graph-root #preview-mesh-bar .button { color: #ffffff; width: 40px; height: 40px; transform-origin: 50% 50%; } #node-editor-graph-root #preview-mesh-bar .button:active { transform: scale(0.9); } #node-editor-graph-root #preview-mesh-bar .button:hover { background: #3f3461; } #node-editor-graph-root #preview-mesh-bar .button.selected { background: #9379e6; } #node-editor-graph-root #preview-mesh-bar .button img { height: 24px; width: 24px; } #node-editor-graph-root #preview-mesh-bar #play-button { grid-column: 3; } #node-editor-graph-root #preview-mesh-bar #color-picker-button { grid-column: 4; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; } #node-editor-graph-root #preview-mesh-bar #color-picker-button img { height: 24px; width: 24px; } #node-editor-graph-root #preview-mesh-bar #color-picker-button #color-picker-image { padding-left: 7px; padding-top: 8px; } #node-editor-graph-root #preview-mesh-bar #color-picker-button #color-picker { transform: scale(0); grid-column: 1; grid-row: 1; } #node-editor-graph-root #preview-mesh-bar #color-picker-button #color-picker-label { width: 100%; background: transparent; cursor: pointer; } #node-editor-graph-root #preview-mesh-bar #preview-new-window { grid-column: 5; } #node-editor-graph-root #preview-mesh-bar select { background-color: #a3a3a3; color: #333333; } #node-editor-graph-root #preview-config-bar { grid-row: 4; grid-column: 1; display: grid; grid-template-columns: 40px 40px 40px 1fr 40px 40px; color: white; align-items: center; font-size: 18px; } #node-editor-graph-root #preview-config-bar.extended { grid-template-columns: 1fr; } #node-editor-graph-root #preview-config-bar .listLine { padding-left: 5px; height: 30px; display: grid; grid-template-columns: 1fr auto; } #node-editor-graph-root #preview-config-bar .listLine .label { grid-column: 1; display: flex; align-items: center; font-size: 14px; } #node-editor-graph-root #preview-config-bar .listLine .options { grid-column: 2; display: flex; align-items: center; margin-right: 5px; } #node-editor-graph-root #preview-config-bar .listLine .options select { width: 115px; } #node-editor-graph-root #preview-config-bar .listLine .copy { display: none; } #node-editor-graph-root #preview-config-bar .button { width: 40px; grid-row: 1; height: 40px; transform-origin: 50% 50%; } #node-editor-graph-root #preview-config-bar .button:hover { background: #3f3461; } #node-editor-graph-root #preview-config-bar .button.selected { background: #9379e6; } #node-editor-graph-root #preview-config-bar .button:active { transform: scale(0.9); } #node-editor-graph-root #preview-config-bar .button img { height: auto; width: 100%; } #node-editor-graph-root #preview-config-bar .button.back-face { grid-column: 6; } #node-editor-graph-root #preview-config-bar .button.depth-pass { grid-column: 5/6; } #node-editor-graph-root #preview-config-bar .button.hemispheric-light { grid-column: 3/4; } #node-editor-graph-root #preview-config-bar .button.direction-light-1 { grid-column: 2/3; } #node-editor-graph-root #preview-config-bar .button.direction-light-0 { grid-column: 1/2; } #node-editor-graph-root #preview { border-top: 1px solid rgb(85, 85, 85); grid-row: 3; grid-column: 1; width: 100%; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; outline: 0 !important; padding: 0 !important; user-select: none; overflow: hidden; } #node-editor-graph-root #preview #preview-canvas { width: 100%; height: 100%; outline: 0 !important; padding: 0 !important; grid-row: 1; grid-column: 1; } #node-editor-graph-root #preview .waitPanel { width: 100%; height: 100%; grid-row: 1; grid-column: 1; color: white; font-size: 18px; align-content: center; justify-content: center; background: rgba(20, 20, 20, 0.95); z-index: 10; display: grid; transition: opacity 250ms; } #node-editor-graph-root #preview .waitPanel.hidden { opacity: 0; pointer-events: none; } #node-editor-graph-root .blocker { visibility: hidden; position: absolute; width: calc(100% - 40px); height: 100%; top: 0; left: 0; background: rgba(20, 20, 20, 0.95); font-family: "acumin-pro"; color: white; font-size: 24px; display: grid; align-content: center; justify-content: center; user-select: none; padding: 20px; text-align: center; } #node-editor-graph-root #log-console { grid-row: 2; grid-column: 3; } #node-editor-graph-root .LightInformationBlock { width: 280px; } #node-editor-graph-root .InputBlock { width: 250px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/main.scss"],names:[],mappings:"AAAA;EACI,aAAA;EACA,4CAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,uBAAA;AACJ;AACI;EACI,2BAAA;EACA,gBAAA;AACR;AAEI;EACI,aAAA;EACA,uBAAA;EACA,qBAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,aAAA;EACA,YAAA;EACA,uBAAA;EACA,kBAAA;EACA,MAAA;EACA,OAAA;AAAR;AAEQ;EACI,kBAAA;AAAZ;AAII;EACI,kBAAA;EACA,cAAA;AAFR;AAKI;EACI,kBAAA;EACA,cAAA;EACA,iBAAA;AAHR;AAMI;EACI,kBAAA;EACA,cAAA;EACA,iBAAA;AAJR;AAOI;EACI,WAAA;EACA,cAAA;EACA,mBAAA;EACA,WAAA;EACA,YAAA;AALR;AAOQ;EACI,aAAA;EACA,WAAA;EACA,YAAA;AALZ;AASI;EACI,kBAAA;EACA,cAAA;EACA,aAAA;EACA,sCAAA;EACA,2BAAA;EACA,YAAA;EACA,gBAAA;AAPR;AAUI;EACI,WAAA;EACA,cAAA;AARR;AAWI;EACI,aAAA;EACA,uBAAA;EACA,qBAAA;EACA,YAAA;EACA,qBAAA;EACA,eAAA;AATR;AAWQ;EACI,6BAAA;EACA,YAAA;EACA,YAAA;AATZ;AAYQ;EACI,6BAAA;EACA,YAAA;AAVZ;AAaQ;EACI,wBAAA;EACA,kBAAA;AAXZ;AAeI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,8CAAA;EACA,mBAAA;EACA,eAAA;EACA,yBAAA;AAbR;AAeQ;EACI,aAAA;AAbZ;AAgBQ;EACI,cAAA;EACA,YAAA;EACA,aAAA;EACA,kCAAA;AAdZ;AAgBY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;AAdhB;AAiBY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;EACA,gBAAA;AAhBhB;AAkBgB;EACI,YAAA;AAhBpB;AAqBQ;EACI,cAAA;EACA,WAAA;EACA,YAAA;EACA,yBAAA;AAnBZ;AAqBY;EACI,qBAAA;AAnBhB;AAsBY;EACI,mBAAA;AApBhB;AAuBY;EACI,mBAAA;AArBhB;AAwBY;EACI,YAAA;EACA,WAAA;AAtBhB;AA0BQ;EACI,cAAA;AAxBZ;AA2BQ;EACI,cAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;AAzBZ;AA2BY;EACI,YAAA;EACA,WAAA;AAzBhB;AA2BY;EACI,iBAAA;EACA,gBAAA;AAzBhB;AA4BY;EACI,mBAAA;EACA,cAAA;EACA,WAAA;AA1BhB;AA6BY;EACI,WAAA;EACA,uBAAA;EACA,eAAA;AA3BhB;AA+BQ;EACI,cAAA;AA7BZ;AAgCQ;EACI,yBAAA;EACA,cAAA;AA9BZ;AAkCI;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,mDAAA;EACA,YAAA;EACA,mBAAA;EACA,eAAA;AAhCR;AAkCQ;EACI,0BAAA;AAhCZ;AAmCQ;EACI,iBAAA;EACA,YAAA;EACA,aAAA;EACA,+BAAA;AAjCZ;AAmCY;EACI,cAAA;EACA,aAAA;EACA,mBAAA;EACA,eAAA;AAjChB;AAoCY;EACI,cAAA;EAEA,aAAA;EACA,mBAAA;EACA,iBAAA;AAnChB;AAqCgB;EACI,YAAA;AAnCpB;AAuCY;EACI,aAAA;AArChB;AAyCQ;EACI,WAAA;EACA,WAAA;EACA,YAAA;EACA,yBAAA;AAvCZ;AAyCY;EACI,mBAAA;AAvChB;AA0CY;EACI,mBAAA;AAxChB;AA2CY;EACI,qBAAA;AAzChB;AA4CY;EACI,YAAA;EACA,WAAA;AA1ChB;AA6CY;EACI,cAAA;AA3ChB;AA8CY;EACI,gBAAA;AA5ChB;AA+CY;EACI,gBAAA;AA7ChB;AA+CY;EACI,gBAAA;AA7ChB;AA+CY;EACI,gBAAA;AA7ChB;AAkDI;EACI,qCAAA;EACA,WAAA;EACA,cAAA;EACA,WAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;EACA,qBAAA;EACA,qBAAA;EACA,iBAAA;EACA,gBAAA;AAhDR;AAkDQ;EACI,WAAA;EACA,YAAA;EACA,qBAAA;EACA,qBAAA;EACA,WAAA;EACA,cAAA;AAhDZ;AAmDQ;EACI,WAAA;EACA,YAAA;EACA,WAAA;EACA,cAAA;EACA,YAAA;EACA,eAAA;EACA,qBAAA;EACA,uBAAA;EACA,kCAAA;EACA,WAAA;EACA,aAAA;EACA,yBAAA;AAjDZ;AAmDY;EACI,UAAA;EACA,oBAAA;AAjDhB;AAsDI;EACI,kBAAA;EACA,kBAAA;EACA,wBAAA;EACA,YAAA;EACA,MAAA;EACA,OAAA;EAEA,kCAAA;EACA,yBAAA;EACA,YAAA;EACA,eAAA;EAEA,aAAA;EACA,qBAAA;EACA,uBAAA;EAEA,iBAAA;EAEA,aAAA;EACA,kBAAA;AAxDR;AA2DI;EACI,WAAA;EACA,cAAA;AAzDR;AA4DI;EACI,YAAA;AA1DR;AA6DI;EACI,YAAA;AA3DR",sourcesContent:[`#node-editor-graph-root {\r display: grid;\r grid-template-rows: calc(100% - 120px) 120px;\r height: 100%;\r width: 100%;\r background: #464646;\r font: 14px "acumin-pro";\r \r &.popup {\r grid-template-columns: 100%;\r overflow: hidden;\r }\r \r .wait-screen {\r display: grid;\r justify-content: center;\r align-content: center;\r height: 100%;\r width: 100%;\r background: #464646;\r opacity: 0.95;\r color: white;\r font: 24px "acumin-pro";\r position: absolute;\r top: 0;\r left: 0;\r \r &.hidden {\r visibility: hidden;\r }\r }\r \r #nmeNodeList {\r grid-row: 1 / span 2;\r grid-column: 1;\r }\r \r #leftGrab {\r grid-row: 1 / span 2;\r grid-column: 2;\r cursor: ew-resize;\r }\r \r #rightGrab {\r grid-row: 1 / span 2;\r grid-column: 4;\r cursor: ew-resize;\r }\r \r .diagram-container {\r grid-row: 1;\r grid-column: 3;\r background: #5f5b60;\r width: 100%;\r height: 100%;\r \r .diagram {\r display: none;\r width: 100%;\r height: 100%;\r }\r }\r \r .nme-right-panel {\r grid-row: 1 / span 2;\r grid-column: 5;\r display: grid;\r grid-template-rows: 1fr 40px auto 40px;\r grid-template-columns: 100%;\r height: 100%;\r overflow-y: auto;\r }\r \r #propertyTab {\r grid-row: 1;\r grid-column: 1;\r }\r \r .button {\r display: grid;\r justify-content: center;\r align-content: center;\r height: auto;\r width: calc(100% / 7);\r cursor: pointer;\r \r &:hover {\r background: rgb(51, 122, 183);\r color: white;\r opacity: 0.8;\r }\r \r &.selected {\r background: rgb(51, 122, 183);\r color: white;\r }\r \r &.align {\r justify-content: stretch;\r text-align: center;\r }\r }\r \r #preview-mesh-bar {\r grid-row: 2;\r grid-column: 1;\r display: grid;\r grid-template-columns: auto 1fr 40px 40px 40px;\r align-items: center;\r font-size: 18px;\r background-color: #555555;\r \r #file-picker {\r display: none;\r }\r \r .listLine {\r grid-column: 1;\r height: 40px;\r display: grid;\r grid-template-columns: 0px 1fr 0px;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r font-size: 14px;\r }\r \r .options {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r margin-left: 5px;\r \r select {\r width: 115px;\r }\r }\r }\r \r .button {\r color: #ffffff;\r width: 40px;\r height: 40px;\r transform-origin: 50% 50%;\r \r &:active {\r transform: scale(0.9);\r }\r \r &:hover {\r background: #3f3461;\r }\r \r &.selected {\r background: #9379e6;\r }\r \r img {\r height: 24px;\r width: 24px;\r }\r }\r \r #play-button {\r grid-column: 3;\r }\r \r #color-picker-button {\r grid-column: 4;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r \r img {\r height: 24px;\r width: 24px;\r }\r #color-picker-image {\r padding-left: 7px;\r padding-top: 8px;\r }\r \r #color-picker {\r transform: scale(0);\r grid-column: 1;\r grid-row: 1;\r }\r \r #color-picker-label {\r width: 100%;\r background: transparent;\r cursor: pointer;\r }\r }\r \r #preview-new-window {\r grid-column: 5;\r }\r \r select {\r background-color: #a3a3a3;\r color: #333333;\r }\r }\r \r #preview-config-bar {\r grid-row: 4;\r grid-column: 1;\r display: grid;\r grid-template-columns: 40px 40px 40px 1fr 40px 40px;\r color: white;\r align-items: center;\r font-size: 18px;\r \r &.extended {\r grid-template-columns: 1fr;\r }\r \r .listLine {\r padding-left: 5px;\r height: 30px;\r display: grid;\r grid-template-columns: 1fr auto;\r \r .label {\r grid-column: 1;\r display: flex;\r align-items: center;\r font-size: 14px;\r }\r \r .options {\r grid-column: 2;\r \r display: flex;\r align-items: center;\r margin-right: 5px;\r \r select {\r width: 115px;\r }\r }\r \r .copy {\r display: none;\r }\r }\r \r .button {\r width: 40px;\r grid-row: 1;\r height: 40px;\r transform-origin: 50% 50%;\r \r &:hover {\r background: #3f3461;\r }\r \r &.selected {\r background: #9379e6;\r }\r \r &:active {\r transform: scale(0.9);\r }\r \r img {\r height: auto;\r width: 100%;\r }\r \r &.back-face {\r grid-column: 6;\r }\r \r &.depth-pass {\r grid-column: 5 / 6;\r }\r \r &.hemispheric-light {\r grid-column: 3 / 4;\r }\r &.direction-light-1 {\r grid-column: 2 / 3;\r }\r &.direction-light-0 {\r grid-column: 1 / 2;\r }\r }\r }\r \r #preview {\r border-top: 1px solid rgb(85, 85, 85);\r grid-row: 3;\r grid-column: 1;\r width: 100%;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r outline: 0 !important;\r padding: 0 !important;\r user-select: none;\r overflow: hidden;\r \r #preview-canvas {\r width: 100%;\r height: 100%;\r outline: 0 !important;\r padding: 0 !important;\r grid-row: 1;\r grid-column: 1;\r }\r \r .waitPanel {\r width: 100%;\r height: 100%;\r grid-row: 1;\r grid-column: 1;\r color: white;\r font-size: 18px;\r align-content: center;\r justify-content: center;\r background: rgba(20, 20, 20, 0.95);\r z-index: 10;\r display: grid;\r transition: opacity 250ms;\r \r &.hidden {\r opacity: 0;\r pointer-events: none;\r }\r }\r }\r \r .blocker {\r visibility: hidden;\r position: absolute;\r width: calc(100% - 40px);\r height: 100%;\r top: 0;\r left: 0;\r \r background: rgba(20, 20, 20, 0.95);\r font-family: "acumin-pro";\r color: white;\r font-size: 24px;\r \r display: grid;\r align-content: center;\r justify-content: center;\r \r user-select: none;\r \r padding: 20px;\r text-align: center;\r }\r \r #log-console {\r grid-row: 2;\r grid-column: 3;\r }\r \r .LightInformationBlock {\r width: 280px;\r }\r \r .InputBlock {\r width: 250px;\r }\r }\r `],sourceRoot:""}]),p.locals={};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/components/MessageDialog.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container { position: absolute; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); display: grid; font-family: "acumin-pro"; top: 0; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog { align-self: center; justify-self: center; min-height: 140px; max-width: 400px; border-radius: 10px; background: white; padding: 10px; display: grid; grid-template-columns: 100%; grid-template-rows: 1fr 50px; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-message { grid-row: 1; grid-column: 1; margin-top: 20px; padding: 10px; font-size: 18px; color: black; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons { grid-row: 2; grid-column: 1; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; color: white; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok { cursor: pointer; justify-self: center; background: green; min-width: 80px; justify-content: center; display: grid; align-content: center; align-self: center; height: 35px; border-radius: 10px; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok:hover { opacity: 0.8; } .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons .\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok.\\---------dev-sharedUiComponents-dist-components-MessageDialog-modules__error { background: red; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/components/MessageDialog.modules.scss"],names:[],mappings:"AAAA;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,8BAAA;EACA,aAAA;EACA,yBAAA;EACA,MAAA;AACJ;AACI;EACI,kBAAA;EACA,oBAAA;EACA,iBAAA;EACA,gBAAA;EACA,mBAAA;EACA,iBAAA;EACA,aAAA;EAEA,aAAA;EACA,2BAAA;EACA,4BAAA;AAAR;AAEQ;EACI,WAAA;EACA,cAAA;EACA,gBAAA;EACA,aAAA;EACA,eAAA;EACA,YAAA;AAAZ;AAGQ;EACI,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;EACA,YAAA;AADZ;AAGY;EACI,eAAA;EACA,oBAAA;EACA,iBAAA;EACA,eAAA;EACA,uBAAA;EACA,aAAA;EACA,qBAAA;EACA,kBAAA;EACA,YAAA;EACA,mBAAA;AADhB;AAGgB;EACI,YAAA;AADpB;AAIgB;EACI,eAAA;AAFpB",sourcesContent:[`:local .dialog-container {\r position: absolute;\r width: 100%;\r height: 100%;\r background: rgba(0.1, 0.1, 0.1, 0.6);\r display: grid;\r font-family: "acumin-pro";\r top: 0;\r \r .dialog {\r align-self: center;\r justify-self: center;\r min-height: 140px;\r max-width: 400px;\r border-radius: 10px;\r background: white;\r padding: 10px;\r \r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 1fr 50px;\r \r .dialog-message {\r grid-row: 1;\r grid-column: 1;\r margin-top: 20px;\r padding: 10px;\r font-size: 18px;\r color: black;\r }\r \r .dialog-buttons {\r grid-row: 2;\r grid-column: 1;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r color: white;\r \r .dialog-button-ok {\r cursor: pointer;\r justify-self: center;\r background: green;\r min-width: 80px;\r justify-content: center;\r display: grid;\r align-content: center;\r align-self: center;\r height: 35px;\r border-radius: 10px;\r \r &:hover {\r opacity: 0.8;\r }\r \r &.error {\r background: red;\r }\r }\r }\r }\r }\r `],sourceRoot:""}]),p.locals={"dialog-container":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-container",dialog:"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog","dialog-message":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-message","dialog-buttons":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-buttons","dialog-button-ok":"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__dialog-button-ok",error:"---------dev-sharedUiComponents-dist-components-MessageDialog-modules__error"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/common.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__hidden { display: none !important; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port { border-radius: 20px; width: 20px; height: 20px; align-self: center; display: grid; grid-template-columns: 100%; grid-template-rows: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__img { width: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port:hover, .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__selected { filter: brightness(2); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine { height: 24px; display: grid; grid-template-rows: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label { align-items: center; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer { grid-row: 1; grid-column: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine { grid-template-columns: 12px calc(100% - 15px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label { grid-row: 1; grid-column: 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port { grid-row: 1; grid-column: 1; transform: translateX(-12px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer { grid-row: 1; grid-column: 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine { grid-template-columns: calc(100% - 10px) 12px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label { grid-row: 1; grid-column: 1; text-align: right; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port { grid-row: 1; grid-column: 2; transform: translateX(2px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__frame-box { position: absolute; background: rgba(72, 72, 72, 0.7); display: grid; grid-template-rows: 40px calc(100% - 40px); grid-template-columns: 100%; box-sizing: border-box; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/common.modules.scss"],names:[],mappings:"AAAA;EACI,wBAAA;AACJ;;AAEA;EACI,mBAAA;EACA,WAAA;EACA,YAAA;EACA,kBAAA;EACA,aAAA;EACA,2BAAA;EACA,wBAAA;AACJ;AACI;EACI,WAAA;AACR;AAEI;EAEI,qBAAA;AADR;;AAKA;EACI,YAAA;EACA,aAAA;EACA,wBAAA;AAFJ;;AAKA;EACI,mBAAA;AAFJ;;AAKA;EACI,WAAA;EACA,cAAA;AAFJ;AAII;EACI,6CAAA;AAFR;AAIQ;EACI,WAAA;EACA,cAAA;AAFZ;AAKQ;EACI,WAAA;EACA,cAAA;EACA,4BAAA;AAHZ;;AAQA;EACI,WAAA;EACA,cAAA;AALJ;AAOI;EACI,6CAAA;AALR;AAOQ;EACI,WAAA;EACA,cAAA;EACA,iBAAA;AALZ;AAQQ;EACI,WAAA;EACA,cAAA;EACA,0BAAA;AANZ;;AAWA;EACI,kBAAA;EACA,iCAAA;EACA,aAAA;EACA,0CAAA;EACA,2BAAA;EACA,sBAAA;AARJ",sourcesContent:[`.hidden {\r display: none !important;\r }\r \r .port {\r border-radius: 20px;\r width: 20px;\r height: 20px;\r align-self: center;\r display: grid;\r grid-template-columns: 100%;\r grid-template-rows: 100%;\r \r .img {\r width: 100%;\r }\r \r &:hover,\r &.selected {\r filter: brightness(2);\r }\r }\r \r .portLine {\r height: 24px;\r display: grid;\r grid-template-rows: 100%;\r }\r \r .port-label {\r align-items: center;\r }\r \r .inputsContainer {\r grid-row: 1;\r grid-column: 1;\r \r .portLine {\r grid-template-columns: 12px calc(100% - 15px);\r \r .port-label {\r grid-row: 1;\r grid-column: 2;\r }\r \r .port {\r grid-row: 1;\r grid-column: 1;\r transform: translateX(-12px);\r }\r }\r }\r \r .outputsContainer {\r grid-row: 1;\r grid-column: 2;\r \r .portLine {\r grid-template-columns: calc(100% - 10px) 12px;\r \r .port-label {\r grid-row: 1;\r grid-column: 1;\r text-align: right;\r }\r \r .port {\r grid-row: 1;\r grid-column: 2;\r transform: translateX(2px);\r }\r }\r }\r \r .frame-box {\r position: absolute;\r background: rgba(72, 72, 72, 0.7);\r display: grid;\r grid-template-rows: 40px calc(100% - 40px);\r grid-template-columns: 100%;\r box-sizing: border-box;\r }\r `],sourceRoot:""}]),p.locals={hidden:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__hidden",port:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port",img:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__img",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__selected",portLine:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__portLine","port-label":"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__port-label",inputsContainer:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__inputsContainer",outputsContainer:"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__outputsContainer","frame-box":"---------dev-sharedUiComponents-dist-nodeGraphSystem-common-modules__frame-box"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphCanvas.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas { width: 100%; height: 100%; margin: 0; padding: 0; font: 14px "acumin-pro"; user-select: none; overflow: hidden; cursor: move; position: relative; background-image: linear-gradient(to right, #4f4e4f 1px, transparent 1px), linear-gradient(to bottom, #4f4e4f 1px, transparent 1px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-container { width: 100%; height: 100%; left: 0; top: 0; transform-origin: left top; display: grid; grid-template-rows: 100%; grid-template-columns: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__frame-container { overflow: visible; grid-row: 1; grid-column: 1; position: relative; width: 100%; height: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-svg-container { grid-row: 1; grid-column: 1; position: relative; width: 100%; height: 100%; overflow: visible; pointer-events: none; z-index: 2; filter: drop-shadow(7px 6px 2px rgba(0, 0, 0, 0.2)); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas-container { grid-row: 1; grid-column: 1; position: relative; width: 100%; height: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-container { pointer-events: none; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-box { z-index: 10; position: absolute; background: rgba(72, 72, 196, 0.5); border: blue solid 2px; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphCanvas.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,SAAA;EACA,UAAA;EACA,uBAAA;EACA,iBAAA;EACA,gBAAA;EACA,YAAA;EACA,kBAAA;EACA,mIAAA;AACJ;;AAEA;EACI,WAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,0BAAA;EACA,aAAA;EACA,wBAAA;EACA,2BAAA;AACJ;;AAEA;EACI,iBAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;AACJ;;AAEA;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;EACA,iBAAA;EACA,oBAAA;EACA,UAAA;EACA,mDAAA;AACJ;;AAEA;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,WAAA;EACA,YAAA;AACJ;;AAEA;EACI,oBAAA;AACJ;;AAEA;EACI,WAAA;EACA,kBAAA;EACA,kCAAA;EACA,sBAAA;AACJ",sourcesContent:[`.graph-canvas {\r width: 100%;\r height: 100%;\r margin: 0;\r padding: 0;\r font: 14px "acumin-pro";\r user-select: none;\r overflow: hidden;\r cursor: move;\r position: relative;\r background-image: linear-gradient(to right, #4f4e4f 1px, transparent 1px), linear-gradient(to bottom, #4f4e4f 1px, transparent 1px);\r }\r \r .graph-container {\r width: 100%;\r height: 100%;\r left: 0;\r top: 0;\r transform-origin: left top;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 100%;\r }\r \r .frame-container {\r overflow: visible;\r grid-row: 1;\r grid-column: 1;\r position: relative;\r width: 100%;\r height: 100%;\r }\r \r .graph-svg-container {\r grid-row: 1;\r grid-column: 1;\r position: relative;\r width: 100%;\r height: 100%;\r overflow: visible;\r pointer-events: none;\r z-index: 2;\r filter: drop-shadow(7px 6px 2px rgba(0, 0, 0, 0.2));\r }\r \r .graph-canvas-container {\r grid-row: 1;\r grid-column: 1;\r position: relative;\r width: 100%;\r height: 100%;\r }\r \r .selection-container {\r pointer-events: none;\r }\r \r .selection-box {\r z-index: 10;\r position: absolute;\r background: rgba(72, 72, 196, 0.5);\r border: blue solid 2px;\r }\r `],sourceRoot:""}]),p.locals={"graph-canvas":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas","graph-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-container","frame-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__frame-container","graph-svg-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-svg-container","graph-canvas-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__graph-canvas-container","selection-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-container","selection-box":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphCanvas-modules__selection-box"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphFrame.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__port-container { margin-top: 6px; margin-bottom: 6px; margin-left: 4px; margin-right: 4px; color: white; grid-row: 2; grid-column: 1; display: grid; grid-template-rows: 100%; grid-template-columns: 50% 50%; z-index: 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-border { grid-row: 1/span 2; grid-column: 1; width: 100%; height: 100%; border: transparent solid 4px; pointer-events: none; box-sizing: border-box; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-comments { display: grid; grid-row: 2; grid-column: 1; padding: 0 10px; font-style: italic; word-wrap: break-word; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__selected.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-border { border-color: white; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header { grid-row: 1; grid-column: 1; background: rgb(72, 72, 72); color: white; text-align: center; display: grid; grid-template-rows: 100%; grid-template-columns: calc(100% - 74px) 30px 7px 30px 7px; align-content: center; overflow: hidden; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-button { cursor: pointer; align-self: center; transform-origin: 50% 50%; transform: scale(1); stroke: transparent; fill: white; display: grid; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-button.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__down { transform: scale(0.9); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-collapse { grid-column: 2; grid-row: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-close { grid-column: 4; grid-row: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-title { grid-column: 1; grid-row: 1; display: grid; height: 100%; width: 100%; align-self: stretch; align-items: center; margin-top: -2px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__right-handle { grid-area: 1/2/3/2; width: 4px; background-color: transparent; cursor: ew-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__right-handle::after { content: ""; width: 8px; position: absolute; top: 0; bottom: 0; margin-left: -4px; cursor: ew-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-right-corner-handle { background-color: transparent; height: 4px; z-index: 21; cursor: ne-resize; width: 4px; margin-left: -6px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-right-corner-handle::after { background-color: transparent; cursor: ne-resize; margin-left: unset; top: -4px; height: 10px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-right-corner-handle { background-color: transparent; height: 0px; z-index: 21; cursor: nw-resize; grid-area: 4/2/4/2; margin-left: -2px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-right-corner-handle::after { background-color: transparent; height: 10px; cursor: nw-resize; top: unset; bottom: -4px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__left-handle { grid-area: 1/1/3/1; width: 4px; background-color: transparent; cursor: ew-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__left-handle::before { content: ""; width: 8px; position: absolute; top: 0; bottom: 0; margin-left: -4px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-left-corner-handle { background-color: transparent; height: 4px; z-index: 21; cursor: nw-resize; width: 4px; margin-left: -4px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-left-corner-handle::before { background-color: transparent; cursor: nw-resize; margin-left: unset; top: -4px; height: 10px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-left-corner-handle { background-color: transparent; height: 0px; z-index: 21; cursor: sw-resize; grid-area: 4/1/4/1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-left-corner-handle::before { background-color: transparent; height: 10px; cursor: sw-resize; top: unset; bottom: -4px; width: 10px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-handle { grid-area: 1/1/1/1; background-color: transparent; height: 4px; cursor: ns-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-handle::before { content: ""; width: 100%; position: absolute; top: -4px; bottom: 100%; right: 0; left: 0; margin-bottom: -8px; cursor: ns-resize; height: 8px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-handle { grid-area: 3/1/3/1; background-color: transparent; height: 4px; cursor: ns-resize; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-handle::after { content: ""; width: 100%; position: absolute; top: 100%; bottom: 0; right: 0; left: 0; margin-top: -8px; cursor: ns-resize; height: 12px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__expanded { font-size: 24px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsed { height: auto !important; width: 200px !important; z-index: 3; font-size: 16px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsedHeader { grid-template-columns: calc(100% - 37px) 30px 7px; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphFrame.modules.scss"],names:[],mappings:"AAAA;EACI,eAAA;EACA,kBAAA;EACA,gBAAA;EACA,iBAAA;EACA,YAAA;EACA,WAAA;EACA,cAAA;EACA,aAAA;EACA,wBAAA;EACA,8BAAA;EACA,UAAA;AACJ;;AAEA;EACI,kBAAA;EACA,cAAA;EACA,WAAA;EACA,YAAA;EACA,6BAAA;EACA,oBAAA;EACA,sBAAA;AACJ;;AAEA;EACI,aAAA;EACA,WAAA;EACA,cAAA;EACA,eAAA;EACA,kBAAA;EACA,qBAAA;AACJ;;AAEA;EACI,mBAAA;AACJ;;AAEA;EACI,WAAA;EACA,cAAA;EACA,2BAAA;EACA,YAAA;EACA,kBAAA;EACA,aAAA;EACA,wBAAA;EACA,0DAAA;EACA,qBAAA;EACA,gBAAA;AACJ;;AAEA;EACI,eAAA;EACA,kBAAA;EACA,yBAAA;EACA,mBAAA;EACA,mBAAA;EACA,WAAA;EACA,aAAA;AACJ;AACI;EACI,qBAAA;AACR;;AAGA;EACI,cAAA;EACA,WAAA;AAAJ;;AAGA;EACI,cAAA;EACA,WAAA;AAAJ;;AAGA;EACI,cAAA;EACA,WAAA;EACA,aAAA;EACA,YAAA;EACA,WAAA;EACA,mBAAA;EACA,mBAAA;EACA,gBAAA;AAAJ;;AAGA;EACI,kBAAA;EACA,UAAA;EACA,6BAAA;EACA,iBAAA;AAAJ;AAEI;EACI,WAAA;EACA,UAAA;EACA,kBAAA;EACA,MAAA;EACA,SAAA;EACA,iBAAA;EACA,iBAAA;AAAR;;AAIA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,iBAAA;AADJ;AAGI;EACI,6BAAA;EACA,iBAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,WAAA;AADR;;AAKA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,kBAAA;EACA,iBAAA;AAFJ;AAII;EACI,6BAAA;EACA,YAAA;EACA,iBAAA;EACA,UAAA;EACA,YAAA;EACA,WAAA;AAFR;;AAMA;EACI,kBAAA;EACA,UAAA;EACA,6BAAA;EACA,iBAAA;AAHJ;AAKI;EACI,WAAA;EACA,UAAA;EACA,kBAAA;EACA,MAAA;EACA,SAAA;EACA,iBAAA;AAHR;;AAOA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,UAAA;EACA,iBAAA;AAJJ;AAMI;EACI,6BAAA;EACA,iBAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,WAAA;AAJR;;AAQA;EACI,6BAAA;EACA,WAAA;EACA,WAAA;EACA,iBAAA;EACA,kBAAA;AALJ;AAOI;EACI,6BAAA;EACA,YAAA;EACA,iBAAA;EACA,UAAA;EACA,YAAA;EACA,WAAA;AALR;;AASA;EACI,kBAAA;EACA,6BAAA;EACA,WAAA;EACA,iBAAA;AANJ;AAQI;EACI,WAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,YAAA;EACA,QAAA;EACA,OAAA;EACA,mBAAA;EACA,iBAAA;EACA,WAAA;AANR;;AAUA;EACI,kBAAA;EACA,6BAAA;EACA,WAAA;EACA,iBAAA;AAPJ;AASI;EACI,WAAA;EACA,WAAA;EACA,kBAAA;EACA,SAAA;EACA,SAAA;EACA,QAAA;EACA,OAAA;EACA,gBAAA;EACA,iBAAA;EACA,YAAA;AAPR;;AAWA;EACI,eAAA;AARJ;;AAWA;EACI,uBAAA;EACA,uBAAA;EACA,UAAA;EACA,eAAA;AARJ;;AAWA;EACI,iDAAA;AARJ",sourcesContent:[`.port-container {\r margin-top: 6px;\r margin-bottom: 6px;\r margin-left: 4px;\r margin-right: 4px;\r color: white;\r grid-row: 2;\r grid-column: 1;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: 50% 50%;\r z-index: 2;\r }\r \r .frame-box-border {\r grid-row: 1 / span 2;\r grid-column: 1;\r width: 100%;\r height: 100%;\r border: transparent solid 4px;\r pointer-events: none;\r box-sizing: border-box;\r }\r \r .frame-comments {\r display: grid;\r grid-row: 2;\r grid-column: 1;\r padding: 0 10px;\r font-style: italic;\r word-wrap: break-word;\r }\r \r .selected.frame-box-border {\r border-color: white;\r }\r \r .frame-box-header {\r grid-row: 1;\r grid-column: 1;\r background: rgba(72, 72, 72, 1);\r color: white;\r text-align: center;\r display: grid;\r grid-template-rows: 100%;\r grid-template-columns: calc(100% - 74px) 30px 7px 30px 7px;\r align-content: center;\r overflow: hidden;\r }\r \r .frame-box-header-button {\r cursor: pointer;\r align-self: center;\r transform-origin: 50% 50%;\r transform: scale(1);\r stroke: transparent;\r fill: white;\r display: grid;\r \r &.down {\r transform: scale(0.9);\r }\r }\r \r .frame-box-header-collapse {\r grid-column: 2;\r grid-row: 1;\r }\r \r .frame-box-header-close {\r grid-column: 4;\r grid-row: 1;\r }\r \r .frame-box-header-title {\r grid-column: 1;\r grid-row: 1;\r display: grid;\r height: 100%;\r width: 100%;\r align-self: stretch;\r align-items: center;\r margin-top: -2px;\r }\r \r .right-handle {\r grid-area: 1 / 2 / 3 / 2;\r width: 4px;\r background-color: transparent;\r cursor: ew-resize;\r \r &::after {\r content: "";\r width: 8px;\r position: absolute;\r top: 0;\r bottom: 0;\r margin-left: -4px;\r cursor: ew-resize;\r }\r }\r \r .top-right-corner-handle {\r background-color: transparent;\r height: 4px;\r z-index: 21;\r cursor: ne-resize;\r width: 4px;\r margin-left: -6px;\r \r &::after {\r background-color: transparent;\r cursor: ne-resize;\r margin-left: unset;\r top: -4px;\r height: 10px;\r width: 10px;\r }\r }\r \r .bottom-right-corner-handle {\r background-color: transparent;\r height: 0px;\r z-index: 21;\r cursor: nw-resize;\r grid-area: 4 / 2 / 4 / 2;\r margin-left: -2px;\r \r &::after {\r background-color: transparent;\r height: 10px;\r cursor: nw-resize;\r top: unset;\r bottom: -4px;\r width: 10px;\r }\r }\r \r .left-handle {\r grid-area: 1 / 1 / 3 / 1;\r width: 4px;\r background-color: transparent;\r cursor: ew-resize;\r \r &::before {\r content: "";\r width: 8px;\r position: absolute;\r top: 0;\r bottom: 0;\r margin-left: -4px;\r }\r }\r \r .top-left-corner-handle {\r background-color: transparent;\r height: 4px;\r z-index: 21;\r cursor: nw-resize;\r width: 4px;\r margin-left: -4px;\r \r &::before {\r background-color: transparent;\r cursor: nw-resize;\r margin-left: unset;\r top: -4px;\r height: 10px;\r width: 10px;\r }\r }\r \r .bottom-left-corner-handle {\r background-color: transparent;\r height: 0px;\r z-index: 21;\r cursor: sw-resize;\r grid-area: 4 / 1 / 4 / 1;\r \r &::before {\r background-color: transparent;\r height: 10px;\r cursor: sw-resize;\r top: unset;\r bottom: -4px;\r width: 10px;\r }\r }\r \r .top-handle {\r grid-area: 1 / 1 / 1 / 1;\r background-color: transparent;\r height: 4px;\r cursor: ns-resize;\r \r &::before {\r content: "";\r width: 100%;\r position: absolute;\r top: -4px;\r bottom: 100%;\r right: 0;\r left: 0;\r margin-bottom: -8px;\r cursor: ns-resize;\r height: 8px;\r }\r }\r \r .bottom-handle {\r grid-area: 3 / 1 / 3 / 1;\r background-color: transparent;\r height: 4px;\r cursor: ns-resize;\r \r &::after {\r content: "";\r width: 100%;\r position: absolute;\r top: 100%;\r bottom: 0;\r right: 0;\r left: 0;\r margin-top: -8px;\r cursor: ns-resize;\r height: 12px;\r }\r }\r \r .expanded {\r font-size: 24px;\r }\r \r .collapsed {\r height: auto !important;\r width: 200px !important;\r z-index: 3;\r font-size: 16px;\r }\r \r .collapsedHeader {\r grid-template-columns: calc(100% - 37px) 30px 7px;\r }\r `],sourceRoot:""}]),p.locals={"port-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__port-container","frame-box-border":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-border","frame-comments":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-comments",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__selected","frame-box-header":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header","frame-box-header-button":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-button",down:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__down","frame-box-header-collapse":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-collapse","frame-box-header-close":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-close","frame-box-header-title":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__frame-box-header-title","right-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__right-handle","top-right-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-right-corner-handle","bottom-right-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-right-corner-handle","left-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__left-handle","top-left-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-left-corner-handle","bottom-left-corner-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-left-corner-handle","top-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__top-handle","bottom-handle":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__bottom-handle",expanded:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__expanded",collapsed:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsed",collapsedHeader:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphFrame-modules__collapsedHeader"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphNode.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__visual { z-index: 4; width: 200px; position: absolute; left: 0; top: 0; background: gray; border: 4px solid black; border-radius: 12px; display: grid; grid-template-rows: 30px auto; grid-template-columns: 100%; color: white; box-shadow: 7px 6px 2px rgba(0, 0, 0, 0.2); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__highlighted { animation: \\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__glow 0.5s infinite alternate; } @keyframes \\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__glow { to { border-color: white; } } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header-container { grid-row: 1; grid-column: 1; position: relative; border: 4px solid black; border-top-right-radius: 7px; border-top-left-radius: 7px; background: black; color: white; transform: scaleX(1.01) translateY(-0.5px); transform-origin: center; display: grid; grid-template-columns: 1fr auto; grid-template-rows: 100%; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerIcon { z-index: 10; align-self: center; user-select: none; pointer-events: none; width: 20px; display: grid; margin-left: 6px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header { font-size: 16px; text-align: center; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerWithIcon { margin-left: calc(20px + 6px); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__connections { grid-row: 2; grid-column: 1; display: grid; grid-template-columns: 50% 50%; transform: scale(1); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__content { min-height: 20px; grid-row: 3; grid-column: 1; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__comments { position: absolute; top: -50px; width: 200px; height: 45px; overflow: hidden; font-style: italic; opacity: 0.8; display: grid; align-items: flex-end; pointer-events: none; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__executionTime { position: absolute; bottom: 1px; width: 195px; height: 20px; overflow: hidden; font-size: 11px; opacity: 0.5; display: grid; align-items: flex-end; justify-content: end; pointer-events: none; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__selected { border-color: white !important; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/graphNode.modules.scss"],names:[],mappings:"AAAA;EACI,UAAA;EACA,YAAA;EACA,kBAAA;EACA,OAAA;EACA,MAAA;EACA,gBAAA;EACA,uBAAA;EACA,mBAAA;EACA,aAAA;EACA,6BAAA;EACA,2BAAA;EACA,YAAA;EACA,0CAAA;AACJ;;AAEA;EACI,gHAAA;AACJ;AAAI;EACI;IACI,mBAAA;EAEV;AACF;;AAEA;EACI,WAAA;EACA,cAAA;EACA,kBAAA;EACA,uBAAA;EACA,4BAAA;EACA,2BAAA;EACA,iBAAA;EACA,YAAA;EACA,0CAAA;EACA,wBAAA;EACA,aAAA;EACA,+BAAA;EACA,wBAAA;AACJ;;AAKA;EACI,WAAA;EACA,kBAAA;EACA,iBAAA;EACA,oBAAA;EACA,WARO;EASP,aAAA;EACA,gBATS;AAOb;;AAKA;EACI,eAAA;EACA,kBAAA;EACA,mBAAA;EACA,uBAAA;EACA,gBAAA;AAFJ;;AAKA;EACI,6BAAA;AAFJ;;AAKA;EACI,WAAA;EACA,cAAA;EAEA,aAAA;EACA,8BAAA;EACA,mBAAA;AAHJ;;AAMA;EACI,gBAAA;EACA,WAAA;EACA,cAAA;AAHJ;;AAMA;EACI,kBAAA;EACA,UAAA;EACA,YAAA;EACA,YAAA;EACA,gBAAA;EACA,kBAAA;EACA,YAAA;EACA,aAAA;EACA,qBAAA;EACA,oBAAA;AAHJ;;AAMA;EACI,kBAAA;EACA,WAAA;EACA,YAAA;EACA,YAAA;EACA,gBAAA;EACA,eAAA;EACA,YAAA;EACA,aAAA;EACA,qBAAA;EACA,oBAAA;EACA,oBAAA;AAHJ;;AAMA;EACI,8BAAA;AAHJ",sourcesContent:[`.visual {\r z-index: 4;\r width: 200px;\r position: absolute;\r left: 0;\r top: 0;\r background: gray;\r border: 4px solid black;\r border-radius: 12px;\r display: grid;\r grid-template-rows: 30px auto;\r grid-template-columns: 100%;\r color: white;\r box-shadow: 7px 6px 2px rgba(0, 0, 0, 0.2);\r }\r \r .highlighted {\r animation: glow 0.5s infinite alternate;\r @keyframes glow {\r to {\r border-color: white;\r }\r }\r }\r \r .header-container {\r grid-row: 1;\r grid-column: 1;\r position: relative;\r border: 4px solid black;\r border-top-right-radius: 7px;\r border-top-left-radius: 7px;\r background: black;\r color: white;\r transform: scaleX(1.01) translateY(-0.5px);\r transform-origin: center;\r display: grid;\r grid-template-columns: 1fr auto;\r grid-template-rows: 100%;\r }\r \r $iconSize: 20px;\r $iconMargin: 6px;\r \r .headerIcon {\r z-index: 10;\r align-self: center;\r user-select: none;\r pointer-events: none;\r width: $iconSize;\r display: grid;\r margin-left: $iconMargin;\r }\r \r .header {\r font-size: 16px;\r text-align: center;\r white-space: nowrap;\r text-overflow: ellipsis;\r overflow: hidden;\r }\r \r .headerWithIcon {\r margin-left: calc(#{$iconSize} + #{$iconMargin});\r }\r \r .connections {\r grid-row: 2;\r grid-column: 1;\r \r display: grid;\r grid-template-columns: 50% 50%;\r transform: scale(1);\r }\r \r .content {\r min-height: 20px;\r grid-row: 3;\r grid-column: 1;\r }\r \r .comments {\r position: absolute;\r top: -50px;\r width: 200px;\r height: 45px;\r overflow: hidden;\r font-style: italic;\r opacity: 0.8;\r display: grid;\r align-items: flex-end;\r pointer-events: none;\r }\r \r .executionTime {\r position: absolute;\r bottom: 1px;\r width: 195px;\r height: 20px;\r overflow: hidden;\r font-size: 11px;\r opacity: 0.5;\r display: grid;\r align-items: flex-end;\r justify-content: end;\r pointer-events: none;\r }\r \r .selected {\r border-color: white !important;\r }\r `],sourceRoot:""}]),p.locals={visual:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__visual",highlighted:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__highlighted",glow:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__glow","header-container":"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header-container",headerIcon:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerIcon",header:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__header",headerWithIcon:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__headerWithIcon",connections:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__connections",content:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__content",comments:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__comments",executionTime:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__executionTime",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-graphNode-modules__selected"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodeLink.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__link { stroke-width: 4px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__link.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selected { stroke: white !important; stroke-dasharray: 10, 2; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__target-candidate { filter: brightness(1.5); stroke-width: 6px; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link { pointer-events: all; stroke-width: 16px; opacity: 0; transition: opacity 75ms; stroke: transparent; cursor: pointer; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link:hover, .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selected { stroke: white !important; opacity: 0.4; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodeLink.modules.scss"],names:[],mappings:"AAAA;EACI,iBAAA;AACJ;AAAI;EACI,wBAAA;EACA,uBAAA;AAER;;AAEA;EACI,uBAAA;EACA,iBAAA;AACJ;;AAEA;EACI,mBAAA;EACA,kBAAA;EACA,UAAA;EACA,wBAAA;EACA,mBAAA;EACA,eAAA;AACJ;AACI;EAEI,wBAAA;EACA,YAAA;AAAR",sourcesContent:[`.link {\r stroke-width: 4px;\r &.selected {\r stroke: white !important;\r stroke-dasharray: 10, 2;\r }\r }\r \r .target-candidate {\r filter: brightness(1.5);\r stroke-width: 6px;\r }\r \r .selection-link {\r pointer-events: all;\r stroke-width: 16px;\r opacity: 0;\r transition: opacity 75ms;\r stroke: transparent;\r cursor: pointer;\r \r &:hover,\r &.selected {\r stroke: white !important;\r opacity: 0.4;\r }\r }\r `],sourceRoot:""}]),p.locals={link:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__link",selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selected","target-candidate":"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__target-candidate","selection-link":"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodeLink-modules__selection-link"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodePort.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__selected { filter: brightness(2); } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__pip { background: green; width: 6px; height: 6px; grid-row: 1; grid-column: 1; align-self: center; justify-self: center; border-radius: 7px; border: 2px solid black; } .\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__pip.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__hidden { display: none; } img { grid-row: 1; grid-column: 1; } img.\\---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__selected { box-shadow: 0 0 0 2px; border-radius: 50%; }`,"",{version:3,sources:["webpack://./../../../dev/sharedUiComponents/dist/nodeGraphSystem/nodePort.modules.scss"],names:[],mappings:"AAAA;EACI,qBAAA;AACJ;;AAEA;EACI,iBAAA;EACA,UAAA;EACA,WAAA;EACA,WAAA;EACA,cAAA;EACA,kBAAA;EACA,oBAAA;EACA,kBAAA;EACA,uBAAA;AACJ;AACI;EACI,aAAA;AACR;;AAGA;EACI,WAAA;EACA,cAAA;AAAJ;;AAGA;EACI,qBAAA;EACA,kBAAA;AAAJ",sourcesContent:[`.selected {\r filter: brightness(2);\r }\r \r .pip {\r background: green;\r width: 6px;\r height: 6px;\r grid-row: 1;\r grid-column: 1;\r align-self: center;\r justify-self: center;\r border-radius: 7px;\r border: 2px solid black;\r \r &.hidden {\r display: none;\r }\r }\r \r img {\r grid-row: 1;\r grid-column: 1;\r }\r \r img.selected {\r box-shadow: 0 0 0 2px;\r border-radius: 50%;\r }\r `],sourceRoot:""}]),p.locals={selected:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__selected",pip:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__pip",hidden:"---------dev-sharedUiComponents-dist-nodeGraphSystem-nodePort-modules__hidden"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/blockNodeData.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-blockNodeData-modules__hidden { display: none !important; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/blockNodeData.modules.scss"],names:[],mappings:"AAAA;EACI,wBAAA;AACJ",sourcesContent:[`.hidden {\r display: none !important;\r }\r `],sourceRoot:""}]),p.locals={hidden:"---------tools-nodeEditor-dist-graphSystem-blockNodeData-modules__hidden"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/clampDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-clampDisplayManager-modules__clampBlock { grid-row: 2; height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/clampDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.clampBlock {\r grid-row: 2;\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={clampBlock:"---------tools-nodeEditor-dist-graphSystem-display-clampDisplayManager-modules__clampBlock"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/common.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block { grid-row: 2; height: 140px; width: 140px; overflow: hidden; border-bottom-left-radius: 7px; border: black 4px solid; border-left: 0px; border-bottom: 0px; } .\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block img { width: 100%; height: 100%; pointer-events: none; } .\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block img.\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__empty { display: none; } .\\---------tools-nodeEditor-dist-graphSystem-display-common-modules__empty { display: none; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/common.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,aAAA;EACA,YAAA;EACA,gBAAA;EACA,8BAAA;EACA,uBAAA;EACA,gBAAA;EACA,kBAAA;AACJ;AACI;EACI,WAAA;EACA,YAAA;EACA,oBAAA;AACR;AACQ;EACI,aAAA;AACZ;;AAIA;EACI,aAAA;AADJ",sourcesContent:[`.texture-block {\r grid-row: 2;\r height: 140px;\r width: 140px;\r overflow: hidden;\r border-bottom-left-radius: 7px;\r border: black 4px solid;\r border-left: 0px;\r border-bottom: 0px;\r \r img {\r width: 100%;\r height: 100%;\r pointer-events: none;\r \r &.empty {\r display: none;\r }\r }\r }\r \r .empty {\r display: none;\r }\r `],sourceRoot:""}]),p.locals={"texture-block":"---------tools-nodeEditor-dist-graphSystem-display-common-modules__texture-block",empty:"---------tools-nodeEditor-dist-graphSystem-display-common-modules__empty"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/curveDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-curveDisplayManager-modules__curve-block { grid-row: 2; height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/curveDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.curve-block {\r grid-row: 2;\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={"curve-block":"---------tools-nodeEditor-dist-graphSystem-display-curveDisplayManager-modules__curve-block"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/elbowDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__elbowBlock { width: 40px !important; grid-template-rows: 0px 40px 0px !important; border-radius: 40px !important; transform: translateY(-7px) !important; } .\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__hidden { display: none; } .\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__translatedConnections { transform: translateY(7px); } .\\---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__roundSelectionBorder { border-radius: 40px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/elbowDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,sBAAA;EACA,2CAAA;EACA,8BAAA;EACA,sCAAA;AACJ;;AAEA;EACI,aAAA;AACJ;;AAEA;EACI,0BAAA;AACJ;;AAEA;EACI,mBAAA;AACJ",sourcesContent:[`.elbowBlock {\r width: 40px !important;\r grid-template-rows: 0px 40px 0px !important;\r border-radius: 40px !important;\r transform: translateY(-7px) !important;\r }\r \r .hidden {\r display: none;\r }\r \r .translatedConnections {\r transform: translateY(7px);\r }\r \r .roundSelectionBorder {\r border-radius: 40px;\r }\r `],sourceRoot:""}]),p.locals={elbowBlock:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__elbowBlock",hidden:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__hidden",translatedConnections:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__translatedConnections",roundSelectionBorder:"---------tools-nodeEditor-dist-graphSystem-display-elbowDisplayManager-modules__roundSelectionBorder"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/gradientDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-gradientDisplayManager-modules__gradientBlock { grid-row: 2; height: 34px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/gradientDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;AACJ",sourcesContent:[`.gradientBlock {\r grid-row: 2;\r height: 34px;\r }\r `],sourceRoot:""}]),p.locals={gradientBlock:"---------tools-nodeEditor-dist-graphSystem-display-gradientDisplayManager-modules__gradientBlock"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/imageSourceDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-imageSourceDisplayManager-modules__image-source-block { margin-top: 5px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/imageSourceDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,eAAA;AACJ",sourcesContent:[`.image-source-block {\r margin-top: 5px;\r }\r `],sourceRoot:""}]),p.locals={"image-source-block":"---------tools-nodeEditor-dist-graphSystem-display-imageSourceDisplayManager-modules__image-source-block"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/inputDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__input-block { grid-row: 2; min-height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px 5px; display: grid; align-content: center; } .\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__input-block.\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__small-font { font-size: 17px; } .\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__constant { border-color: #464348; background: #464348; } .\\---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__inspector { border-color: #66491b; background: #66491b; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/inputDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,gBAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,kBAAA;EACA,aAAA;EACA,qBAAA;AACJ;AACI;EACI,eAAA;AACR;;AAGA;EACI,qBAAA;EACA,mBAAA;AAAJ;;AAGA;EACI,qBAAA;EACA,mBAAA;AAAJ",sourcesContent:[`.input-block {\r grid-row: 2;\r min-height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px 5px;\r display: grid;\r align-content: center;\r \r &.small-font {\r font-size: 17px;\r }\r }\r \r .constant {\r border-color: #464348;\r background: #464348;\r }\r \r .inspector {\r border-color: #66491b;\r background: #66491b;\r }\r `],sourceRoot:""}]),p.locals={"input-block":"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__input-block","small-font":"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__small-font",constant:"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__constant",inspector:"---------tools-nodeEditor-dist-graphSystem-display-inputDisplayManager-modules__inspector"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/remapDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-remapDisplayManager-modules__remap-block { height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/remapDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.remap-block {\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={"remap-block":"---------tools-nodeEditor-dist-graphSystem-display-remapDisplayManager-modules__remap-block"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/textureDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__regular-texture-block { margin-top: 80px; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reduced-texture-block { margin-top: 30px; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reflection-block { grid-row: 3 !important; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__triplanar-texture-block { margin-top: 155px; } .\\---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__refraction-texture-block { margin-top: 80px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/textureDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,gBAAA;AACJ;;AAEA;EACI,gBAAA;AACJ;;AAEA;EACI,sBAAA;AACJ;;AAEA;EACI,iBAAA;AACJ;;AAEA;EACI,gBAAA;AACJ",sourcesContent:[`.regular-texture-block {\r margin-top: 80px;\r }\r \r .reduced-texture-block {\r margin-top: 30px;\r }\r \r .reflection-block {\r grid-row: 3 !important;\r }\r \r .triplanar-texture-block {\r margin-top: 155px;\r }\r \r .refraction-texture-block {\r margin-top: 80px;\r }\r `],sourceRoot:""}]),p.locals={"regular-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__regular-texture-block","reduced-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reduced-texture-block","reflection-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__reflection-block","triplanar-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__triplanar-texture-block","refraction-texture-block":"---------tools-nodeEditor-dist-graphSystem-display-textureDisplayManager-modules__refraction-texture-block"};const m=p},"../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[4].use[2]!../../../tools/nodeEditor/dist/graphSystem/display/trigonometryDisplayManager.modules.scss":(o,l,c)=>{c.r(l),c.d(l,{default:()=>m});var u=c("../../../../node_modules/css-loader/dist/runtime/sourceMaps.js"),h=c.n(u),d=c("../../../../node_modules/css-loader/dist/runtime/api.js"),f=c.n(d),p=f()(h());p.push([o.id,`.\\---------tools-nodeEditor-dist-graphSystem-display-trigonometryDisplayManager-modules__trigonometry-block { grid-row: 2; height: 34px; text-align: center; font-size: 18px; font-weight: bold; margin: 0 10px; }`,"",{version:3,sources:["webpack://./../../../tools/nodeEditor/dist/graphSystem/display/trigonometryDisplayManager.modules.scss"],names:[],mappings:"AAAA;EACI,WAAA;EACA,YAAA;EACA,kBAAA;EACA,eAAA;EACA,iBAAA;EACA,cAAA;AACJ",sourcesContent:[`.trigonometry-block {\r grid-row: 2;\r height: 34px;\r text-align: center;\r font-size: 18px;\r font-weight: bold;\r margin: 0 10px;\r }\r `],sourceRoot:""}]),p.locals={"trigonometry-block":"---------tools-nodeEditor-dist-graphSystem-display-trigonometryDisplayManager-modules__trigonometry-block"};const m=p},"../../../../node_modules/@fortawesome/react-fontawesome/index.es.js":(o,l,c)=>{c.r(l),c.d(l,{FontAwesomeIcon:()=>W});var u=c("../../../../node_modules/@fortawesome/fontawesome-svg-core/index.mjs"),h=c("../../../../node_modules/prop-types/index.js"),d=c.n(h),f=c("../../../../node_modules/react/index.js");function p(q,ie){var ae=Object.keys(q);if(Object.getOwnPropertySymbols){var ue=Object.getOwnPropertySymbols(q);ie&&(ue=ue.filter(function(ce){return Object.getOwnPropertyDescriptor(q,ce).enumerable})),ae.push.apply(ae,ue)}return ae}function m(q){for(var ie=1;ie=0)&&(ae[ce]=q[ce]);return ae}function v(q,ie){if(q==null)return{};var ae=y(q,ie),ue,ce;if(Object.getOwnPropertySymbols){var N=Object.getOwnPropertySymbols(q);for(ce=0;ce=0)&&Object.prototype.propertyIsEnumerable.call(q,ue)&&(ae[ue]=q[ue])}return ae}function x(q){return A(q)||b(q)||C(q)||w()}function A(q){if(Array.isArray(q))return T(q)}function b(q){if(typeof Symbol<"u"&&q[Symbol.iterator]!=null||q["@@iterator"]!=null)return Array.from(q)}function C(q,ie){if(q){if(typeof q=="string")return T(q,ie);var ae=Object.prototype.toString.call(q).slice(8,-1);if(ae==="Object"&&q.constructor&&(ae=q.constructor.name),ae==="Map"||ae==="Set")return Array.from(q);if(ae==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(ae))return T(q,ie)}}function T(q,ie){(ie==null||ie>q.length)&&(ie=q.length);for(var ae=0,ue=new Array(ie);ae2&&arguments[2]!==void 0?arguments[2]:{};if(typeof ie=="string")return ie;var ue=(ie.children||[]).map(function(te){return V(q,te)}),ce=Object.keys(ie.attributes||{}).reduce(function(te,oe){var ne=ie.attributes[oe];switch(oe){case"class":te.attrs.className=ne,delete ie.attributes.class;break;case"style":te.attrs.style=k(ne);break;default:oe.indexOf("aria-")===0||oe.indexOf("data-")===0?te.attrs[oe.toLowerCase()]=ne:te.attrs[R(oe)]=ne}return te},{attrs:{}}),N=ae.style,B=N===void 0?{}:N,Y=v(ae,I);return ce.attrs.style=m(m({},ce.attrs.style),B),q.apply(void 0,[ie.tag,m(m({},ce.attrs),Y)].concat(x(ue)))}var H=!1;try{H=!1}catch{}function j(){if(!H&&console&&typeof console.error=="function"){var q;(q=console).error.apply(q,arguments)}}function z(q){if(q&&g(q)==="object"&&q.prefix&&q.iconName&&q.icon)return q;if(u.parse.icon)return u.parse.icon(q);if(q===null)return null;if(q&&g(q)==="object"&&q.prefix&&q.iconName)return q;if(Array.isArray(q)&&q.length===2)return{prefix:q[0],iconName:q[1]};if(typeof q=="string")return{prefix:"fas",iconName:q}}function K(q,ie){return Array.isArray(ie)&&ie.length>0||!Array.isArray(ie)&&ie?_({},q,ie):{}}var U={border:!1,className:"",mask:null,maskId:null,fixedWidth:!1,inverse:!1,flip:!1,icon:null,listItem:!1,pull:null,pulse:!1,rotation:null,size:null,spin:!1,spinPulse:!1,spinReverse:!1,beat:!1,fade:!1,beatFade:!1,bounce:!1,shake:!1,symbol:!1,title:"",titleId:null,transform:null,swapOpacity:!1},W=f.forwardRef(function(q,ie){var ae=m(m({},U),q),ue=ae.icon,ce=ae.mask,N=ae.symbol,B=ae.className,Y=ae.title,te=ae.titleId,oe=ae.maskId,ne=z(ue),pe=K("classes",[].concat(x(P(ae)),x((B||"").split(" ")))),ye=K("transform",typeof ae.transform=="string"?u.parse.transform(ae.transform):ae.transform),Ie=K("mask",z(ce)),Ne=(0,u.icon)(ne,m(m(m(m({},pe),ye),Ie),{},{symbol:N,title:Y,titleId:te,maskId:oe}));if(!Ne)return j("Could not find icon",ne),null;var Ve=Ne.abstract,nt={ref:ie};return Object.keys(ae).forEach(function(Ke){U.hasOwnProperty(Ke)||(nt[Ke]=ae[Ke])}),Z(Ve[0],nt)});W.displayName="FontAwesomeIcon",W.propTypes={beat:d().bool,border:d().bool,beatFade:d().bool,bounce:d().bool,className:d().string,fade:d().bool,flash:d().bool,mask:d().oneOfType([d().object,d().array,d().string]),maskId:d().string,fixedWidth:d().bool,inverse:d().bool,flip:d().oneOf([!0,!1,"horizontal","vertical","both"]),icon:d().oneOfType([d().object,d().array,d().string]),listItem:d().bool,pull:d().oneOf(["right","left"]),pulse:d().bool,rotation:d().oneOf([0,90,180,270]),shake:d().bool,size:d().oneOf(["2xs","xs","sm","lg","xl","2xl","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:d().bool,spinPulse:d().bool,spinReverse:d().bool,symbol:d().oneOfType([d().bool,d().string]),title:d().string,titleId:d().string,transform:d().oneOfType([d().string,d().object]),swapOpacity:d().bool};var Z=V.bind(null,f.createElement)},"../../../../node_modules/css-loader/dist/runtime/api.js":o=>{o.exports=function(l){var c=[];return c.toString=function(){return this.map(function(h){var d="",f=typeof h[5]<"u";return h[4]&&(d+="@supports (".concat(h[4],") {")),h[2]&&(d+="@media ".concat(h[2]," {")),f&&(d+="@layer".concat(h[5].length>0?" ".concat(h[5]):""," {")),d+=l(h),f&&(d+="}"),h[2]&&(d+="}"),h[4]&&(d+="}"),d}).join("")},c.i=function(h,d,f,p,m){typeof h=="string"&&(h=[[null,h,void 0]]);var g={};if(f)for(var _=0;_"u"||(x[1]="@layer".concat(x[5].length>0?" ".concat(x[5]):""," {").concat(x[1],"}")),x[5]=m),d&&(x[2]&&(x[1]="@media ".concat(x[2]," {").concat(x[1],"}")),x[2]=d),p&&(x[4]?(x[1]="@supports (".concat(x[4],") {").concat(x[1],"}"),x[4]=p):x[4]="".concat(p)),c.push(x))}},c}},"../../../../node_modules/css-loader/dist/runtime/sourceMaps.js":o=>{o.exports=function(l){var c=l[1],u=l[3];if(!u)return c;if(typeof btoa=="function"){var h=btoa(unescape(encodeURIComponent(JSON.stringify(u)))),d="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(h),f="/*# ".concat(d," */");return[c].concat([f]).join(` `)}return[c].join(` `)}},"../../../../node_modules/dagre/index.js":(o,l,c)=>{o.exports={graphlib:c("../../../../node_modules/dagre/lib/graphlib.js"),layout:c("../../../../node_modules/dagre/lib/layout.js"),debug:c("../../../../node_modules/dagre/lib/debug.js"),util:{time:c("../../../../node_modules/dagre/lib/util.js").time,notime:c("../../../../node_modules/dagre/lib/util.js").notime},version:c("../../../../node_modules/dagre/lib/version.js")}},"../../../../node_modules/dagre/lib/acyclic.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/greedy-fas.js");o.exports={run:d,undo:p};function d(m){var g=m.graph().acyclicer==="greedy"?h(m,_(m)):f(m);u.forEach(g,function(y){var v=m.edge(y);m.removeEdge(y),v.forwardName=y.name,v.reversed=!0,m.setEdge(y.w,y.v,v,u.uniqueId("rev"))});function _(y){return function(v){return y.edge(v).weight}}}function f(m){var g=[],_={},y={};function v(x){u.has(y,x)||(y[x]=!0,_[x]=!0,u.forEach(m.outEdges(x),function(A){u.has(_,A.w)?g.push(A):v(A.w)}),delete _[x])}return u.forEach(m.nodes(),v),g}function p(m){u.forEach(m.edges(),function(g){var _=m.edge(g);if(_.reversed){m.removeEdge(g);var y=_.forwardName;delete _.reversed,delete _.forwardName,m.setEdge(g.w,g.v,_,y)}})}},"../../../../node_modules/dagre/lib/add-border-segments.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/util.js");o.exports=d;function d(p){function m(g){var _=p.children(g),y=p.node(g);if(_.length&&u.forEach(_,m),u.has(y,"minRank")){y.borderLeft=[],y.borderRight=[];for(var v=y.minRank,x=y.maxRank+1;v{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports={adjust:h,undo:d};function h(v){var x=v.graph().rankdir.toLowerCase();(x==="lr"||x==="rl")&&f(v)}function d(v){var x=v.graph().rankdir.toLowerCase();(x==="bt"||x==="rl")&&m(v),(x==="lr"||x==="rl")&&(_(v),f(v))}function f(v){u.forEach(v.nodes(),function(x){p(v.node(x))}),u.forEach(v.edges(),function(x){p(v.edge(x))})}function p(v){var x=v.width;v.width=v.height,v.height=x}function m(v){u.forEach(v.nodes(),function(x){g(v.node(x))}),u.forEach(v.edges(),function(x){var A=v.edge(x);u.forEach(A.points,g),u.has(A,"y")&&g(A)})}function g(v){v.y=-v.y}function _(v){u.forEach(v.nodes(),function(x){y(v.node(x))}),u.forEach(v.edges(),function(x){var A=v.edge(x);u.forEach(A.points,y),u.has(A,"x")&&y(A)})}function y(v){var x=v.x;v.x=v.y,v.y=x}},"../../../../node_modules/dagre/lib/data/list.js":o=>{o.exports=l;function l(){var h={};h._next=h._prev=h,this._sentinel=h}l.prototype.dequeue=function(){var h=this._sentinel,d=h._prev;if(d!==h)return c(d),d},l.prototype.enqueue=function(h){var d=this._sentinel;h._prev&&h._next&&c(h),h._next=d._next,d._next._prev=h,d._next=h,h._prev=d},l.prototype.toString=function(){for(var h=[],d=this._sentinel,f=d._prev;f!==d;)h.push(JSON.stringify(f,u)),f=f._prev;return"["+h.join(", ")+"]"};function c(h){h._prev._next=h._next,h._next._prev=h._prev,delete h._next,delete h._prev}function u(h,d){if(h!=="_next"&&h!=="_prev")return d}},"../../../../node_modules/dagre/lib/debug.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/util.js"),d=c("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports={debugOrdering:f};function f(p){var m=h.buildLayerMatrix(p),g=new d({compound:!0,multigraph:!0}).setGraph({});return u.forEach(p.nodes(),function(_){g.setNode(_,{label:_}),g.setParent(_,"layer"+p.node(_).rank)}),u.forEach(p.edges(),function(_){g.setEdge(_.v,_.w,{},_.name)}),u.forEach(m,function(_,y){var v="layer"+y;g.setNode(v,{rank:"same"}),u.reduce(_,function(x,A){return g.setEdge(x,A,{style:"invis"}),A})}),g}},"../../../../node_modules/dagre/lib/graphlib.js":(o,l,c)=>{var u;try{u=c("../../../../node_modules/graphlib/index.js")}catch{}u||(u=window.graphlib),o.exports=u},"../../../../node_modules/dagre/lib/greedy-fas.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/graphlib.js").Graph,d=c("../../../../node_modules/dagre/lib/data/list.js");o.exports=p;var f=u.constant(1);function p(v,x){if(v.nodeCount()<=1)return[];var A=_(v,x||f),b=m(A.graph,A.buckets,A.zeroIdx);return u.flatten(u.map(b,function(C){return v.outEdges(C.v,C.w)}),!0)}function m(v,x,A){for(var b=[],C=x[x.length-1],T=x[0],w;v.nodeCount();){for(;w=T.dequeue();)g(v,x,A,w);for(;w=C.dequeue();)g(v,x,A,w);if(v.nodeCount()){for(var P=x.length-2;P>0;--P)if(w=x[P].dequeue(),w){b=b.concat(g(v,x,A,w,!0));break}}}return b}function g(v,x,A,b,C){var T=C?[]:void 0;return u.forEach(v.inEdges(b.v),function(w){var P=v.edge(w),M=v.node(w.v);C&&T.push({v:w.v,w:w.w}),M.out-=P,y(x,A,M)}),u.forEach(v.outEdges(b.v),function(w){var P=v.edge(w),M=w.w,R=v.node(M);R.in-=P,y(x,A,R)}),v.removeNode(b.v),T}function _(v,x){var A=new h,b=0,C=0;u.forEach(v.nodes(),function(P){A.setNode(P,{v:P,in:0,out:0})}),u.forEach(v.edges(),function(P){var M=A.edge(P.v,P.w)||0,R=x(P),I=M+R;A.setEdge(P.v,P.w,I),C=Math.max(C,A.node(P.v).out+=R),b=Math.max(b,A.node(P.w).in+=R)});var T=u.range(C+b+3).map(function(){return new d}),w=b+1;return u.forEach(A.nodes(),function(P){y(T,w,A.node(P))}),{graph:A,buckets:T,zeroIdx:w}}function y(v,x,A){A.out?A.in?v[A.out-A.in+x].enqueue(A):v[v.length-1].enqueue(A):v[0].enqueue(A)}},"../../../../node_modules/dagre/lib/layout.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/acyclic.js"),d=c("../../../../node_modules/dagre/lib/normalize.js"),f=c("../../../../node_modules/dagre/lib/rank/index.js"),p=c("../../../../node_modules/dagre/lib/util.js").normalizeRanks,m=c("../../../../node_modules/dagre/lib/parent-dummy-chains.js"),g=c("../../../../node_modules/dagre/lib/util.js").removeEmptyRanks,_=c("../../../../node_modules/dagre/lib/nesting-graph.js"),y=c("../../../../node_modules/dagre/lib/add-border-segments.js"),v=c("../../../../node_modules/dagre/lib/coordinate-system.js"),x=c("../../../../node_modules/dagre/lib/order/index.js"),A=c("../../../../node_modules/dagre/lib/position/index.js"),b=c("../../../../node_modules/dagre/lib/util.js"),C=c("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports=T;function T(ne,pe){var ye=pe&&pe.debugTiming?b.time:b.notime;ye("layout",function(){var Ie=ye(" buildLayoutGraph",function(){return z(ne)});ye(" runLayout",function(){w(Ie,ye)}),ye(" updateInputGraph",function(){P(ne,Ie)})})}function w(ne,pe){pe(" makeSpaceForEdgeLabels",function(){K(ne)}),pe(" removeSelfEdges",function(){N(ne)}),pe(" acyclic",function(){h.run(ne)}),pe(" nestingGraph.run",function(){_.run(ne)}),pe(" rank",function(){f(b.asNonCompoundGraph(ne))}),pe(" injectEdgeLabelProxies",function(){U(ne)}),pe(" removeEmptyRanks",function(){g(ne)}),pe(" nestingGraph.cleanup",function(){_.cleanup(ne)}),pe(" normalizeRanks",function(){p(ne)}),pe(" assignRankMinMax",function(){W(ne)}),pe(" removeEdgeLabelProxies",function(){Z(ne)}),pe(" normalize.run",function(){d.run(ne)}),pe(" parentDummyChains",function(){m(ne)}),pe(" addBorderSegments",function(){y(ne)}),pe(" order",function(){x(ne)}),pe(" insertSelfEdges",function(){B(ne)}),pe(" adjustCoordinateSystem",function(){v.adjust(ne)}),pe(" position",function(){A(ne)}),pe(" positionSelfEdges",function(){Y(ne)}),pe(" removeBorderNodes",function(){ce(ne)}),pe(" normalize.undo",function(){d.undo(ne)}),pe(" fixupEdgeLabelCoords",function(){ae(ne)}),pe(" undoCoordinateSystem",function(){v.undo(ne)}),pe(" translateGraph",function(){q(ne)}),pe(" assignNodeIntersects",function(){ie(ne)}),pe(" reversePoints",function(){ue(ne)}),pe(" acyclic.undo",function(){h.undo(ne)})}function P(ne,pe){u.forEach(ne.nodes(),function(ye){var Ie=ne.node(ye),Ne=pe.node(ye);Ie&&(Ie.x=Ne.x,Ie.y=Ne.y,pe.children(ye).length&&(Ie.width=Ne.width,Ie.height=Ne.height))}),u.forEach(ne.edges(),function(ye){var Ie=ne.edge(ye),Ne=pe.edge(ye);Ie.points=Ne.points,u.has(Ne,"x")&&(Ie.x=Ne.x,Ie.y=Ne.y)}),ne.graph().width=pe.graph().width,ne.graph().height=pe.graph().height}var M=["nodesep","edgesep","ranksep","marginx","marginy"],R={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},I=["acyclicer","ranker","rankdir","align"],L=["width","height"],k={width:0,height:0},V=["minlen","weight","width","height","labeloffset"],H={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},j=["labelpos"];function z(ne){var pe=new C({multigraph:!0,compound:!0}),ye=oe(ne.graph());return pe.setGraph(u.merge({},R,te(ye,M),u.pick(ye,I))),u.forEach(ne.nodes(),function(Ie){var Ne=oe(ne.node(Ie));pe.setNode(Ie,u.defaults(te(Ne,L),k)),pe.setParent(Ie,ne.parent(Ie))}),u.forEach(ne.edges(),function(Ie){var Ne=oe(ne.edge(Ie));pe.setEdge(Ie,u.merge({},H,te(Ne,V),u.pick(Ne,j)))}),pe}function K(ne){var pe=ne.graph();pe.ranksep/=2,u.forEach(ne.edges(),function(ye){var Ie=ne.edge(ye);Ie.minlen*=2,Ie.labelpos.toLowerCase()!=="c"&&(pe.rankdir==="TB"||pe.rankdir==="BT"?Ie.width+=Ie.labeloffset:Ie.height+=Ie.labeloffset)})}function U(ne){u.forEach(ne.edges(),function(pe){var ye=ne.edge(pe);if(ye.width&&ye.height){var Ie=ne.node(pe.v),Ne=ne.node(pe.w),Ve={rank:(Ne.rank-Ie.rank)/2+Ie.rank,e:pe};b.addDummyNode(ne,"edge-proxy",Ve,"_ep")}})}function W(ne){var pe=0;u.forEach(ne.nodes(),function(ye){var Ie=ne.node(ye);Ie.borderTop&&(Ie.minRank=ne.node(Ie.borderTop).rank,Ie.maxRank=ne.node(Ie.borderBottom).rank,pe=u.max(pe,Ie.maxRank))}),ne.graph().maxRank=pe}function Z(ne){u.forEach(ne.nodes(),function(pe){var ye=ne.node(pe);ye.dummy==="edge-proxy"&&(ne.edge(ye.e).labelRank=ye.rank,ne.removeNode(pe))})}function q(ne){var pe=Number.POSITIVE_INFINITY,ye=0,Ie=Number.POSITIVE_INFINITY,Ne=0,Ve=ne.graph(),nt=Ve.marginx||0,Ke=Ve.marginy||0;function Et(ft){var Tt=ft.x,Zt=ft.y,Ji=ft.width,hi=ft.height;pe=Math.min(pe,Tt-Ji/2),ye=Math.max(ye,Tt+Ji/2),Ie=Math.min(Ie,Zt-hi/2),Ne=Math.max(Ne,Zt+hi/2)}u.forEach(ne.nodes(),function(ft){Et(ne.node(ft))}),u.forEach(ne.edges(),function(ft){var Tt=ne.edge(ft);u.has(Tt,"x")&&Et(Tt)}),pe-=nt,Ie-=Ke,u.forEach(ne.nodes(),function(ft){var Tt=ne.node(ft);Tt.x-=pe,Tt.y-=Ie}),u.forEach(ne.edges(),function(ft){var Tt=ne.edge(ft);u.forEach(Tt.points,function(Zt){Zt.x-=pe,Zt.y-=Ie}),u.has(Tt,"x")&&(Tt.x-=pe),u.has(Tt,"y")&&(Tt.y-=Ie)}),Ve.width=ye-pe+nt,Ve.height=Ne-Ie+Ke}function ie(ne){u.forEach(ne.edges(),function(pe){var ye=ne.edge(pe),Ie=ne.node(pe.v),Ne=ne.node(pe.w),Ve,nt;ye.points?(Ve=ye.points[0],nt=ye.points[ye.points.length-1]):(ye.points=[],Ve=Ne,nt=Ie),ye.points.unshift(b.intersectRect(Ie,Ve)),ye.points.push(b.intersectRect(Ne,nt))})}function ae(ne){u.forEach(ne.edges(),function(pe){var ye=ne.edge(pe);if(u.has(ye,"x"))switch((ye.labelpos==="l"||ye.labelpos==="r")&&(ye.width-=ye.labeloffset),ye.labelpos){case"l":ye.x-=ye.width/2+ye.labeloffset;break;case"r":ye.x+=ye.width/2+ye.labeloffset;break}})}function ue(ne){u.forEach(ne.edges(),function(pe){var ye=ne.edge(pe);ye.reversed&&ye.points.reverse()})}function ce(ne){u.forEach(ne.nodes(),function(pe){if(ne.children(pe).length){var ye=ne.node(pe),Ie=ne.node(ye.borderTop),Ne=ne.node(ye.borderBottom),Ve=ne.node(u.last(ye.borderLeft)),nt=ne.node(u.last(ye.borderRight));ye.width=Math.abs(nt.x-Ve.x),ye.height=Math.abs(Ne.y-Ie.y),ye.x=Ve.x+ye.width/2,ye.y=Ie.y+ye.height/2}}),u.forEach(ne.nodes(),function(pe){ne.node(pe).dummy==="border"&&ne.removeNode(pe)})}function N(ne){u.forEach(ne.edges(),function(pe){if(pe.v===pe.w){var ye=ne.node(pe.v);ye.selfEdges||(ye.selfEdges=[]),ye.selfEdges.push({e:pe,label:ne.edge(pe)}),ne.removeEdge(pe)}})}function B(ne){var pe=b.buildLayerMatrix(ne);u.forEach(pe,function(ye){var Ie=0;u.forEach(ye,function(Ne,Ve){var nt=ne.node(Ne);nt.order=Ve+Ie,u.forEach(nt.selfEdges,function(Ke){b.addDummyNode(ne,"selfedge",{width:Ke.label.width,height:Ke.label.height,rank:nt.rank,order:Ve+ ++Ie,e:Ke.e,label:Ke.label},"_se")}),delete nt.selfEdges})})}function Y(ne){u.forEach(ne.nodes(),function(pe){var ye=ne.node(pe);if(ye.dummy==="selfedge"){var Ie=ne.node(ye.e.v),Ne=Ie.x+Ie.width/2,Ve=Ie.y,nt=ye.x-Ne,Ke=Ie.height/2;ne.setEdge(ye.e,ye.label),ne.removeNode(pe),ye.label.points=[{x:Ne+2*nt/3,y:Ve-Ke},{x:Ne+5*nt/6,y:Ve-Ke},{x:Ne+nt,y:Ve},{x:Ne+5*nt/6,y:Ve+Ke},{x:Ne+2*nt/3,y:Ve+Ke}],ye.label.x=ye.x,ye.label.y=ye.y}})}function te(ne,pe){return u.mapValues(u.pick(ne,pe),Number)}function oe(ne){var pe={};return u.forEach(ne,function(ye,Ie){pe[Ie.toLowerCase()]=ye}),pe}},"../../../../node_modules/dagre/lib/lodash.js":(o,l,c)=>{var u;try{u={cloneDeep:c("../../../../node_modules/lodash/cloneDeep.js"),constant:c("../../../../node_modules/lodash/constant.js"),defaults:c("../../../../node_modules/lodash/defaults.js"),each:c("../../../../node_modules/lodash/each.js"),filter:c("../../../../node_modules/lodash/filter.js"),find:c("../../../../node_modules/lodash/find.js"),flatten:c("../../../../node_modules/lodash/flatten.js"),forEach:c("../../../../node_modules/lodash/forEach.js"),forIn:c("../../../../node_modules/lodash/forIn.js"),has:c("../../../../node_modules/lodash/has.js"),isUndefined:c("../../../../node_modules/lodash/isUndefined.js"),last:c("../../../../node_modules/lodash/last.js"),map:c("../../../../node_modules/lodash/map.js"),mapValues:c("../../../../node_modules/lodash/mapValues.js"),max:c("../../../../node_modules/lodash/max.js"),merge:c("../../../../node_modules/lodash/merge.js"),min:c("../../../../node_modules/lodash/min.js"),minBy:c("../../../../node_modules/lodash/minBy.js"),now:c("../../../../node_modules/lodash/now.js"),pick:c("../../../../node_modules/lodash/pick.js"),range:c("../../../../node_modules/lodash/range.js"),reduce:c("../../../../node_modules/lodash/reduce.js"),sortBy:c("../../../../node_modules/lodash/sortBy.js"),uniqueId:c("../../../../node_modules/lodash/uniqueId.js"),values:c("../../../../node_modules/lodash/values.js"),zipObject:c("../../../../node_modules/lodash/zipObject.js")}}catch{}u||(u=window._),o.exports=u},"../../../../node_modules/dagre/lib/nesting-graph.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/util.js");o.exports={run:d,cleanup:g};function d(_){var y=h.addDummyNode(_,"root",{},"_root"),v=p(_),x=u.max(u.values(v))-1,A=2*x+1;_.graph().nestingRoot=y,u.forEach(_.edges(),function(C){_.edge(C).minlen*=A});var b=m(_)+1;u.forEach(_.children(),function(C){f(_,y,A,b,x,v,C)}),_.graph().nodeRankFactor=A}function f(_,y,v,x,A,b,C){var T=_.children(C);if(!T.length){C!==y&&_.setEdge(y,C,{weight:0,minlen:v});return}var w=h.addBorderNode(_,"_bt"),P=h.addBorderNode(_,"_bb"),M=_.node(C);_.setParent(w,C),M.borderTop=w,_.setParent(P,C),M.borderBottom=P,u.forEach(T,function(R){f(_,y,v,x,A,b,R);var I=_.node(R),L=I.borderTop?I.borderTop:R,k=I.borderBottom?I.borderBottom:R,V=I.borderTop?x:2*x,H=L!==k?1:A-b[C]+1;_.setEdge(w,L,{weight:V,minlen:H,nestingEdge:!0}),_.setEdge(k,P,{weight:V,minlen:H,nestingEdge:!0})}),_.parent(C)||_.setEdge(y,w,{weight:0,minlen:A+b[C]})}function p(_){var y={};function v(x,A){var b=_.children(x);b&&b.length&&u.forEach(b,function(C){v(C,A+1)}),y[x]=A}return u.forEach(_.children(),function(x){v(x,1)}),y}function m(_){return u.reduce(_.edges(),function(y,v){return y+_.edge(v).weight},0)}function g(_){var y=_.graph();_.removeNode(y.nestingRoot),delete y.nestingRoot,u.forEach(_.edges(),function(v){var x=_.edge(v);x.nestingEdge&&_.removeEdge(v)})}},"../../../../node_modules/dagre/lib/normalize.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/util.js");o.exports={run:d,undo:p};function d(m){m.graph().dummyChains=[],u.forEach(m.edges(),function(g){f(m,g)})}function f(m,g){var _=g.v,y=m.node(_).rank,v=g.w,x=m.node(v).rank,A=g.name,b=m.edge(g),C=b.labelRank;if(x!==y+1){m.removeEdge(g);var T,w,P;for(P=0,++y;y{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(d,f,p){var m={},g;u.forEach(p,function(_){for(var y=d.parent(_),v,x;y;){if(v=d.parent(y),v?(x=m[v],m[v]=y):(x=g,g=y),x&&x!==y){f.setEdge(x,y);return}y=v}})}},"../../../../node_modules/dagre/lib/order/barycenter.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(d,f){return u.map(f,function(p){var m=d.inEdges(p);if(m.length){var g=u.reduce(m,function(_,y){var v=d.edge(y),x=d.node(y.v);return{sum:_.sum+v.weight*x.order,weight:_.weight+v.weight}},{sum:0,weight:0});return{v:p,barycenter:g.sum/g.weight,weight:g.weight}}else return{v:p}})}},"../../../../node_modules/dagre/lib/order/build-layer-graph.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports=d;function d(p,m,g){var _=f(p),y=new h({compound:!0}).setGraph({root:_}).setDefaultNodeLabel(function(v){return p.node(v)});return u.forEach(p.nodes(),function(v){var x=p.node(v),A=p.parent(v);(x.rank===m||x.minRank<=m&&m<=x.maxRank)&&(y.setNode(v),y.setParent(v,A||_),u.forEach(p[g](v),function(b){var C=b.v===v?b.w:b.v,T=y.edge(C,v),w=u.isUndefined(T)?0:T.weight;y.setEdge(C,v,{weight:p.edge(b).weight+w})}),u.has(x,"minRank")&&y.setNode(v,{borderLeft:x.borderLeft[m],borderRight:x.borderRight[m]}))}),y}function f(p){for(var m;p.hasNode(m=u.uniqueId("_root")););return m}},"../../../../node_modules/dagre/lib/order/cross-count.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(f,p){for(var m=0,g=1;g0;)C%2&&(T+=x[C+1]),C=C-1>>1,x[C]+=b.weight;A+=b.weight*T})),A}},"../../../../node_modules/dagre/lib/order/index.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/order/init-order.js"),d=c("../../../../node_modules/dagre/lib/order/cross-count.js"),f=c("../../../../node_modules/dagre/lib/order/sort-subgraph.js"),p=c("../../../../node_modules/dagre/lib/order/build-layer-graph.js"),m=c("../../../../node_modules/dagre/lib/order/add-subgraph-constraints.js"),g=c("../../../../node_modules/dagre/lib/graphlib.js").Graph,_=c("../../../../node_modules/dagre/lib/util.js");o.exports=y;function y(b){var C=_.maxRank(b),T=v(b,u.range(1,C+1),"inEdges"),w=v(b,u.range(C-1,-1,-1),"outEdges"),P=h(b);A(b,P);for(var M=Number.POSITIVE_INFINITY,R,I=0,L=0;L<4;++I,++L){x(I%2?T:w,I%4>=2),P=_.buildLayerMatrix(b);var k=d(b,P);k{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(d){var f={},p=u.filter(d.nodes(),function(v){return!d.children(v).length}),m=u.max(u.map(p,function(v){return d.node(v).rank})),g=u.map(u.range(m+1),function(){return[]});function _(v){if(!u.has(f,v)){f[v]=!0;var x=d.node(v);g[x.rank].push(v),u.forEach(d.successors(v),_)}}var y=u.sortBy(p,function(v){return d.node(v).rank});return u.forEach(y,_),g}},"../../../../node_modules/dagre/lib/order/resolve-conflicts.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(p,m){var g={};u.forEach(p,function(y,v){var x=g[y.v]={indegree:0,in:[],out:[],vs:[y.v],i:v};u.isUndefined(y.barycenter)||(x.barycenter=y.barycenter,x.weight=y.weight)}),u.forEach(m.edges(),function(y){var v=g[y.v],x=g[y.w];!u.isUndefined(v)&&!u.isUndefined(x)&&(x.indegree++,v.out.push(g[y.w]))});var _=u.filter(g,function(y){return!y.indegree});return d(_)}function d(p){var m=[];function g(v){return function(x){x.merged||(u.isUndefined(x.barycenter)||u.isUndefined(v.barycenter)||x.barycenter>=v.barycenter)&&f(v,x)}}function _(v){return function(x){x.in.push(v),--x.indegree===0&&p.push(x)}}for(;p.length;){var y=p.pop();m.push(y),u.forEach(y.in.reverse(),g(y)),u.forEach(y.out,_(y))}return u.map(u.filter(m,function(v){return!v.merged}),function(v){return u.pick(v,["vs","i","barycenter","weight"])})}function f(p,m){var g=0,_=0;p.weight&&(g+=p.barycenter*p.weight,_+=p.weight),m.weight&&(g+=m.barycenter*m.weight,_+=m.weight),p.vs=m.vs.concat(p.vs),p.barycenter=g/_,p.weight=_,p.i=Math.min(m.i,p.i),m.merged=!0}},"../../../../node_modules/dagre/lib/order/sort-subgraph.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/order/barycenter.js"),d=c("../../../../node_modules/dagre/lib/order/resolve-conflicts.js"),f=c("../../../../node_modules/dagre/lib/order/sort.js");o.exports=p;function p(_,y,v,x){var A=_.children(y),b=_.node(y),C=b?b.borderLeft:void 0,T=b?b.borderRight:void 0,w={};C&&(A=u.filter(A,function(k){return k!==C&&k!==T}));var P=h(_,A);u.forEach(P,function(k){if(_.children(k.v).length){var V=p(_,k.v,v,x);w[k.v]=V,u.has(V,"barycenter")&&g(k,V)}});var M=d(P,v);m(M,w);var R=f(M,x);if(C&&(R.vs=u.flatten([C,R.vs,T],!0),_.predecessors(C).length)){var I=_.node(_.predecessors(C)[0]),L=_.node(_.predecessors(T)[0]);u.has(R,"barycenter")||(R.barycenter=0,R.weight=0),R.barycenter=(R.barycenter*R.weight+I.order+L.order)/(R.weight+2),R.weight+=2}return R}function m(_,y){u.forEach(_,function(v){v.vs=u.flatten(v.vs.map(function(x){return y[x]?y[x].vs:x}),!0)})}function g(_,y){u.isUndefined(_.barycenter)?(_.barycenter=y.barycenter,_.weight=y.weight):(_.barycenter=(_.barycenter*_.weight+y.barycenter*y.weight)/(_.weight+y.weight),_.weight+=y.weight)}},"../../../../node_modules/dagre/lib/order/sort.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/util.js");o.exports=d;function d(m,g){var _=h.partition(m,function(w){return u.has(w,"barycenter")}),y=_.lhs,v=u.sortBy(_.rhs,function(w){return-w.i}),x=[],A=0,b=0,C=0;y.sort(p(!!g)),C=f(x,v,C),u.forEach(y,function(w){C+=w.vs.length,x.push(w.vs),A+=w.barycenter*w.weight,b+=w.weight,C=f(x,v,C)});var T={vs:u.flatten(x,!0)};return b&&(T.barycenter=A/b,T.weight=b),T}function f(m,g,_){for(var y;g.length&&(y=u.last(g)).i<=_;)g.pop(),m.push(y.vs),_++;return _}function p(m){return function(g,_){return g.barycenter<_.barycenter?-1:g.barycenter>_.barycenter?1:m?_.i-g.i:g.i-_.i}}},"../../../../node_modules/dagre/lib/parent-dummy-chains.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(p){var m=f(p);u.forEach(p.graph().dummyChains,function(g){for(var _=p.node(g),y=_.edgeObj,v=d(p,m,y.v,y.w),x=v.path,A=v.lca,b=0,C=x[b],T=!0;g!==y.w;){if(_=p.node(g),T){for(;(C=x[b])!==A&&p.node(C).maxRank<_.rank;)b++;C===A&&(T=!1)}if(!T){for(;bx||A>m[b].lim));for(C=b,b=_;(b=p.parent(b))!==C;)v.push(b);return{path:y.concat(v.reverse()),lca:C}}function f(p){var m={},g=0;function _(y){var v=g;u.forEach(p.children(y),_),m[y]={low:v,lim:g++}}return u.forEach(p.children(),_),m}},"../../../../node_modules/dagre/lib/position/bk.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/graphlib.js").Graph,d=c("../../../../node_modules/dagre/lib/util.js");o.exports={positionX:T,findType1Conflicts:f,findType2Conflicts:p,addConflict:g,hasConflict:_,verticalAlignment:y,horizontalCompaction:v,alignCoordinates:b,findSmallestWidthAlignment:A,balance:C};function f(M,R){var I={};function L(k,V){var H=0,j=0,z=k.length,K=u.last(V);return u.forEach(V,function(U,W){var Z=m(M,U),q=Z?M.node(Z).order:z;(Z||U===K)&&(u.forEach(V.slice(j,W+1),function(ie){u.forEach(M.predecessors(ie),function(ae){var ue=M.node(ae),ce=ue.order;(ceK)&&g(I,Z,U)})})}function k(V,H){var j=-1,z,K=0;return u.forEach(H,function(U,W){if(M.node(U).dummy==="border"){var Z=M.predecessors(U);Z.length&&(z=M.node(Z[0]).order,L(H,K,W,j,z),K=W,j=z)}L(H,K,H.length,z,V.length)}),H}return u.reduce(R,k),I}function m(M,R){if(M.node(R).dummy)return u.find(M.predecessors(R),function(I){return M.node(I).dummy})}function g(M,R,I){if(R>I){var L=R;R=I,I=L}var k=M[R];k||(M[R]=k={}),k[I]=!0}function _(M,R,I){if(R>I){var L=R;R=I,I=L}return u.has(M[R],I)}function y(M,R,I,L){var k={},V={},H={};return u.forEach(R,function(j){u.forEach(j,function(z,K){k[z]=z,V[z]=z,H[z]=K})}),u.forEach(R,function(j){var z=-1;u.forEach(j,function(K){var U=L(K);if(U.length){U=u.sortBy(U,function(ae){return H[ae]});for(var W=(U.length-1)/2,Z=Math.floor(W),q=Math.ceil(W);Z<=q;++Z){var ie=U[Z];V[K]===K&&z{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/util.js"),d=c("../../../../node_modules/dagre/lib/position/bk.js").positionX;o.exports=f;function f(m){m=h.asNonCompoundGraph(m),p(m),u.forEach(d(m),function(g,_){m.node(_).x=g})}function p(m){var g=h.buildLayerMatrix(m),_=m.graph().ranksep,y=0;u.forEach(g,function(v){var x=u.max(u.map(v,function(A){return m.node(A).height}));u.forEach(v,function(A){m.node(A).y=y+x/2}),y+=x+_})}},"../../../../node_modules/dagre/lib/rank/feasible-tree.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/graphlib.js").Graph,d=c("../../../../node_modules/dagre/lib/rank/util.js").slack;o.exports=f;function f(_){var y=new h({directed:!1}),v=_.nodes()[0],x=_.nodeCount();y.setNode(v,{});for(var A,b;p(y,_){var u=c("../../../../node_modules/dagre/lib/rank/util.js"),h=u.longestPath,d=c("../../../../node_modules/dagre/lib/rank/feasible-tree.js"),f=c("../../../../node_modules/dagre/lib/rank/network-simplex.js");o.exports=p;function p(y){switch(y.graph().ranker){case"network-simplex":_(y);break;case"tight-tree":g(y);break;case"longest-path":m(y);break;default:_(y)}}var m=h;function g(y){h(y),d(y)}function _(y){f(y)}},"../../../../node_modules/dagre/lib/rank/network-simplex.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/rank/feasible-tree.js"),d=c("../../../../node_modules/dagre/lib/rank/util.js").slack,f=c("../../../../node_modules/dagre/lib/rank/util.js").longestPath,p=c("../../../../node_modules/dagre/lib/graphlib.js").alg.preorder,m=c("../../../../node_modules/dagre/lib/graphlib.js").alg.postorder,g=c("../../../../node_modules/dagre/lib/util.js").simplify;o.exports=_,_.initLowLimValues=A,_.initCutValues=y,_.calcCutValue=x,_.leaveEdge=C,_.enterEdge=T,_.exchangeEdges=w;function _(I){I=g(I),f(I);var L=h(I);A(L),y(L,I);for(var k,V;k=C(L);)V=T(L,I,k),w(L,I,k,V)}function y(I,L){var k=m(I,I.nodes());k=k.slice(0,k.length-1),u.forEach(k,function(V){v(I,L,V)})}function v(I,L,k){var V=I.node(k),H=V.parent;I.edge(k,H).cutvalue=x(I,L,k)}function x(I,L,k){var V=I.node(k),H=V.parent,j=!0,z=L.edge(k,H),K=0;return z||(j=!1,z=L.edge(H,k)),K=z.weight,u.forEach(L.nodeEdges(k),function(U){var W=U.v===k,Z=W?U.w:U.v;if(Z!==H){var q=W===j,ie=L.edge(U).weight;if(K+=q?ie:-ie,M(I,k,Z)){var ae=I.edge(k,Z).cutvalue;K+=q?-ae:ae}}}),K}function A(I,L){arguments.length<2&&(L=I.nodes()[0]),b(I,{},1,L)}function b(I,L,k,V,H){var j=k,z=I.node(V);return L[V]=!0,u.forEach(I.neighbors(V),function(K){u.has(L,K)||(k=b(I,L,k,K,V))}),z.low=j,z.lim=k++,H?z.parent=H:delete z.parent,k}function C(I){return u.find(I.edges(),function(L){return I.edge(L).cutvalue<0})}function T(I,L,k){var V=k.v,H=k.w;L.hasEdge(V,H)||(V=k.w,H=k.v);var j=I.node(V),z=I.node(H),K=j,U=!1;j.lim>z.lim&&(K=z,U=!0);var W=u.filter(L.edges(),function(Z){return U===R(I,I.node(Z.v),K)&&U!==R(I,I.node(Z.w),K)});return u.minBy(W,function(Z){return d(L,Z)})}function w(I,L,k,V){var H=k.v,j=k.w;I.removeEdge(H,j),I.setEdge(V.v,V.w,{}),A(I),y(I,L),P(I,L)}function P(I,L){var k=u.find(I.nodes(),function(H){return!L.node(H).parent}),V=p(I,k);V=V.slice(1),u.forEach(V,function(H){var j=I.node(H).parent,z=L.edge(H,j),K=!1;z||(z=L.edge(j,H),K=!0),L.node(H).rank=L.node(j).rank+(K?z.minlen:-z.minlen)})}function M(I,L,k){return I.hasEdge(L,k)}function R(I,L,k){return k.low<=L.lim&&L.lim<=k.lim}},"../../../../node_modules/dagre/lib/rank/util.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports={longestPath:h,slack:d};function h(f){var p={};function m(g){var _=f.node(g);if(u.has(p,g))return _.rank;p[g]=!0;var y=u.min(u.map(f.outEdges(g),function(v){return m(v.w)-f.edge(v).minlen}));return(y===Number.POSITIVE_INFINITY||y===void 0||y===null)&&(y=0),_.rank=y}u.forEach(f.sources(),m)}function d(f,p){return f.node(p.w).rank-f.node(p.v).rank-f.edge(p).minlen}},"../../../../node_modules/dagre/lib/util.js":(o,l,c)=>{var u=c("../../../../node_modules/dagre/lib/lodash.js"),h=c("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports={addDummyNode:d,simplify:f,asNonCompoundGraph:p,successorWeights:m,predecessorWeights:g,intersectRect:_,buildLayerMatrix:y,normalizeRanks:v,removeEmptyRanks:x,addBorderNode:A,maxRank:b,partition:C,time:T,notime:w};function d(P,M,R,I){var L;do L=u.uniqueId(I);while(P.hasNode(L));return R.dummy=M,P.setNode(L,R),L}function f(P){var M=new h().setGraph(P.graph());return u.forEach(P.nodes(),function(R){M.setNode(R,P.node(R))}),u.forEach(P.edges(),function(R){var I=M.edge(R.v,R.w)||{weight:0,minlen:1},L=P.edge(R);M.setEdge(R.v,R.w,{weight:I.weight+L.weight,minlen:Math.max(I.minlen,L.minlen)})}),M}function p(P){var M=new h({multigraph:P.isMultigraph()}).setGraph(P.graph());return u.forEach(P.nodes(),function(R){P.children(R).length||M.setNode(R,P.node(R))}),u.forEach(P.edges(),function(R){M.setEdge(R,P.edge(R))}),M}function m(P){var M=u.map(P.nodes(),function(R){var I={};return u.forEach(P.outEdges(R),function(L){I[L.w]=(I[L.w]||0)+P.edge(L).weight}),I});return u.zipObject(P.nodes(),M)}function g(P){var M=u.map(P.nodes(),function(R){var I={};return u.forEach(P.inEdges(R),function(L){I[L.v]=(I[L.v]||0)+P.edge(L).weight}),I});return u.zipObject(P.nodes(),M)}function _(P,M){var R=P.x,I=P.y,L=M.x-R,k=M.y-I,V=P.width/2,H=P.height/2;if(!L&&!k)throw new Error("Not possible to find intersection inside of the rectangle");var j,z;return Math.abs(k)*V>Math.abs(L)*H?(k<0&&(H=-H),j=H*L/k,z=H):(L<0&&(V=-V),j=V,z=V*k/L),{x:R+j,y:I+z}}function y(P){var M=u.map(u.range(b(P)+1),function(){return[]});return u.forEach(P.nodes(),function(R){var I=P.node(R),L=I.rank;u.isUndefined(L)||(M[L][I.order]=R)}),M}function v(P){var M=u.min(u.map(P.nodes(),function(R){return P.node(R).rank}));u.forEach(P.nodes(),function(R){var I=P.node(R);u.has(I,"rank")&&(I.rank-=M)})}function x(P){var M=u.min(u.map(P.nodes(),function(k){return P.node(k).rank})),R=[];u.forEach(P.nodes(),function(k){var V=P.node(k).rank-M;R[V]||(R[V]=[]),R[V].push(k)});var I=0,L=P.graph().nodeRankFactor;u.forEach(R,function(k,V){u.isUndefined(k)&&V%L!==0?--I:I&&u.forEach(k,function(H){P.node(H).rank+=I})})}function A(P,M,R,I){var L={width:0,height:0};return arguments.length>=4&&(L.rank=R,L.order=I),d(P,"border",L,M)}function b(P){return u.max(u.map(P.nodes(),function(M){var R=P.node(M).rank;if(!u.isUndefined(R))return R}))}function C(P,M){var R={lhs:[],rhs:[]};return u.forEach(P,function(I){M(I)?R.lhs.push(I):R.rhs.push(I)}),R}function T(P,M){var R=u.now();try{return M()}finally{console.log(P+" time: "+(u.now()-R)+"ms")}}function w(P,M){return M()}},"../../../../node_modules/dagre/lib/version.js":o=>{o.exports="0.8.5"},"../../../../node_modules/graphlib/index.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/index.js");o.exports={Graph:u.Graph,json:c("../../../../node_modules/graphlib/lib/json.js"),alg:c("../../../../node_modules/graphlib/lib/alg/index.js"),version:u.version}},"../../../../node_modules/graphlib/lib/alg/components.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=h;function h(d){var f={},p=[],m;function g(_){u.has(f,_)||(f[_]=!0,m.push(_),u.each(d.successors(_),g),u.each(d.predecessors(_),g))}return u.each(d.nodes(),function(_){m=[],g(_),m.length&&p.push(m)}),p}},"../../../../node_modules/graphlib/lib/alg/dfs.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=h;function h(f,p,m){u.isArray(p)||(p=[p]);var g=(f.isDirected()?f.successors:f.neighbors).bind(f),_=[],y={};return u.each(p,function(v){if(!f.hasNode(v))throw new Error("Graph does not have node: "+v);d(f,v,m==="post",y,g,_)}),_}function d(f,p,m,g,_,y){u.has(g,p)||(g[p]=!0,m||y.push(p),u.each(_(p),function(v){d(f,v,m,g,_,y)}),m&&y.push(p))}},"../../../../node_modules/graphlib/lib/alg/dijkstra-all.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/alg/dijkstra.js"),h=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=d;function d(f,p,m){return h.transform(f.nodes(),function(g,_){g[_]=u(f,_,p,m)},{})}},"../../../../node_modules/graphlib/lib/alg/dijkstra.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js"),h=c("../../../../node_modules/graphlib/lib/data/priority-queue.js");o.exports=f;var d=u.constant(1);function f(m,g,_,y){return p(m,String(g),_||d,y||function(v){return m.outEdges(v)})}function p(m,g,_,y){var v={},x=new h,A,b,C=function(T){var w=T.v!==A?T.v:T.w,P=v[w],M=_(T),R=b.distance+M;if(M<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+T+" Weight: "+M);R0&&(A=x.removeMin(),b=v[A],b.distance!==Number.POSITIVE_INFINITY);)y(A).forEach(C);return v}},"../../../../node_modules/graphlib/lib/alg/find-cycles.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js"),h=c("../../../../node_modules/graphlib/lib/alg/tarjan.js");o.exports=d;function d(f){return u.filter(h(f),function(p){return p.length>1||p.length===1&&f.hasEdge(p[0],p[0])})}},"../../../../node_modules/graphlib/lib/alg/floyd-warshall.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=d;var h=u.constant(1);function d(p,m,g){return f(p,m||h,g||function(_){return p.outEdges(_)})}function f(p,m,g){var _={},y=p.nodes();return y.forEach(function(v){_[v]={},_[v][v]={distance:0},y.forEach(function(x){v!==x&&(_[v][x]={distance:Number.POSITIVE_INFINITY})}),g(v).forEach(function(x){var A=x.v===v?x.w:x.v,b=m(x);_[v][A]={distance:b,predecessor:v}})}),y.forEach(function(v){var x=_[v];y.forEach(function(A){var b=_[A];y.forEach(function(C){var T=b[v],w=x[C],P=b[C],M=T.distance+w.distance;M{o.exports={components:c("../../../../node_modules/graphlib/lib/alg/components.js"),dijkstra:c("../../../../node_modules/graphlib/lib/alg/dijkstra.js"),dijkstraAll:c("../../../../node_modules/graphlib/lib/alg/dijkstra-all.js"),findCycles:c("../../../../node_modules/graphlib/lib/alg/find-cycles.js"),floydWarshall:c("../../../../node_modules/graphlib/lib/alg/floyd-warshall.js"),isAcyclic:c("../../../../node_modules/graphlib/lib/alg/is-acyclic.js"),postorder:c("../../../../node_modules/graphlib/lib/alg/postorder.js"),preorder:c("../../../../node_modules/graphlib/lib/alg/preorder.js"),prim:c("../../../../node_modules/graphlib/lib/alg/prim.js"),tarjan:c("../../../../node_modules/graphlib/lib/alg/tarjan.js"),topsort:c("../../../../node_modules/graphlib/lib/alg/topsort.js")}},"../../../../node_modules/graphlib/lib/alg/is-acyclic.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/alg/topsort.js");o.exports=h;function h(d){try{u(d)}catch(f){if(f instanceof u.CycleException)return!1;throw f}return!0}},"../../../../node_modules/graphlib/lib/alg/postorder.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/alg/dfs.js");o.exports=h;function h(d,f){return u(d,f,"post")}},"../../../../node_modules/graphlib/lib/alg/preorder.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/alg/dfs.js");o.exports=h;function h(d,f){return u(d,f,"pre")}},"../../../../node_modules/graphlib/lib/alg/prim.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js"),h=c("../../../../node_modules/graphlib/lib/graph.js"),d=c("../../../../node_modules/graphlib/lib/data/priority-queue.js");o.exports=f;function f(p,m){var g=new h,_={},y=new d,v;function x(b){var C=b.v===v?b.w:b.v,T=y.priority(C);if(T!==void 0){var w=m(b);w0;){if(v=y.removeMin(),u.has(_,v))g.setEdge(v,_[v]);else{if(A)throw new Error("Input graph is not connected: "+p);A=!0}p.nodeEdges(v).forEach(x)}return g}},"../../../../node_modules/graphlib/lib/alg/tarjan.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=h;function h(d){var f=0,p=[],m={},g=[];function _(y){var v=m[y]={onStack:!0,lowlink:f,index:f++};if(p.push(y),d.successors(y).forEach(function(b){u.has(m,b)?m[b].onStack&&(v.lowlink=Math.min(v.lowlink,m[b].index)):(_(b),v.lowlink=Math.min(v.lowlink,m[b].lowlink))}),v.lowlink===v.index){var x=[],A;do A=p.pop(),m[A].onStack=!1,x.push(A);while(y!==A);g.push(x)}}return d.nodes().forEach(function(y){u.has(m,y)||_(y)}),g}},"../../../../node_modules/graphlib/lib/alg/topsort.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=h,h.CycleException=d;function h(f){var p={},m={},g=[];function _(y){if(u.has(m,y))throw new d;u.has(p,y)||(m[y]=!0,p[y]=!0,u.each(f.predecessors(y),_),delete m[y],g.push(y))}if(u.each(f.sinks(),_),u.size(p)!==f.nodeCount())throw new d;return g}function d(){}d.prototype=new Error},"../../../../node_modules/graphlib/lib/data/priority-queue.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=h;function h(){this._arr=[],this._keyIndices={}}h.prototype.size=function(){return this._arr.length},h.prototype.keys=function(){return this._arr.map(function(d){return d.key})},h.prototype.has=function(d){return u.has(this._keyIndices,d)},h.prototype.priority=function(d){var f=this._keyIndices[d];if(f!==void 0)return this._arr[f].priority},h.prototype.min=function(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key},h.prototype.add=function(d,f){var p=this._keyIndices;if(d=String(d),!u.has(p,d)){var m=this._arr,g=m.length;return p[d]=g,m.push({key:d,priority:f}),this._decrease(g),!0}return!1},h.prototype.removeMin=function(){this._swap(0,this._arr.length-1);var d=this._arr.pop();return delete this._keyIndices[d.key],this._heapify(0),d.key},h.prototype.decrease=function(d,f){var p=this._keyIndices[d];if(f>this._arr[p].priority)throw new Error("New priority is greater than current priority. Key: "+d+" Old: "+this._arr[p].priority+" New: "+f);this._arr[p].priority=f,this._decrease(p)},h.prototype._heapify=function(d){var f=this._arr,p=2*d,m=p+1,g=d;p>1,!(f[m].priority{var u=c("../../../../node_modules/graphlib/lib/lodash.js");o.exports=p;var h="\0",d="\0",f="";function p(x){this._isDirected=u.has(x,"directed")?x.directed:!0,this._isMultigraph=u.has(x,"multigraph")?x.multigraph:!1,this._isCompound=u.has(x,"compound")?x.compound:!1,this._label=void 0,this._defaultNodeLabelFn=u.constant(void 0),this._defaultEdgeLabelFn=u.constant(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children[d]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={}}p.prototype._nodeCount=0,p.prototype._edgeCount=0,p.prototype.isDirected=function(){return this._isDirected},p.prototype.isMultigraph=function(){return this._isMultigraph},p.prototype.isCompound=function(){return this._isCompound},p.prototype.setGraph=function(x){return this._label=x,this},p.prototype.graph=function(){return this._label},p.prototype.setDefaultNodeLabel=function(x){return u.isFunction(x)||(x=u.constant(x)),this._defaultNodeLabelFn=x,this},p.prototype.nodeCount=function(){return this._nodeCount},p.prototype.nodes=function(){return u.keys(this._nodes)},p.prototype.sources=function(){var x=this;return u.filter(this.nodes(),function(A){return u.isEmpty(x._in[A])})},p.prototype.sinks=function(){var x=this;return u.filter(this.nodes(),function(A){return u.isEmpty(x._out[A])})},p.prototype.setNodes=function(x,A){var b=arguments,C=this;return u.each(x,function(T){b.length>1?C.setNode(T,A):C.setNode(T)}),this},p.prototype.setNode=function(x,A){return u.has(this._nodes,x)?(arguments.length>1&&(this._nodes[x]=A),this):(this._nodes[x]=arguments.length>1?A:this._defaultNodeLabelFn(x),this._isCompound&&(this._parent[x]=d,this._children[x]={},this._children[d][x]=!0),this._in[x]={},this._preds[x]={},this._out[x]={},this._sucs[x]={},++this._nodeCount,this)},p.prototype.node=function(x){return this._nodes[x]},p.prototype.hasNode=function(x){return u.has(this._nodes,x)},p.prototype.removeNode=function(x){var A=this;if(u.has(this._nodes,x)){var b=function(C){A.removeEdge(A._edgeObjs[C])};delete this._nodes[x],this._isCompound&&(this._removeFromParentsChildList(x),delete this._parent[x],u.each(this.children(x),function(C){A.setParent(C)}),delete this._children[x]),u.each(u.keys(this._in[x]),b),delete this._in[x],delete this._preds[x],u.each(u.keys(this._out[x]),b),delete this._out[x],delete this._sucs[x],--this._nodeCount}return this},p.prototype.setParent=function(x,A){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(u.isUndefined(A))A=d;else{A+="";for(var b=A;!u.isUndefined(b);b=this.parent(b))if(b===x)throw new Error("Setting "+A+" as parent of "+x+" would create a cycle");this.setNode(A)}return this.setNode(x),this._removeFromParentsChildList(x),this._parent[x]=A,this._children[A][x]=!0,this},p.prototype._removeFromParentsChildList=function(x){delete this._children[this._parent[x]][x]},p.prototype.parent=function(x){if(this._isCompound){var A=this._parent[x];if(A!==d)return A}},p.prototype.children=function(x){if(u.isUndefined(x)&&(x=d),this._isCompound){var A=this._children[x];if(A)return u.keys(A)}else{if(x===d)return this.nodes();if(this.hasNode(x))return[]}},p.prototype.predecessors=function(x){var A=this._preds[x];if(A)return u.keys(A)},p.prototype.successors=function(x){var A=this._sucs[x];if(A)return u.keys(A)},p.prototype.neighbors=function(x){var A=this.predecessors(x);if(A)return u.union(A,this.successors(x))},p.prototype.isLeaf=function(x){var A;return this.isDirected()?A=this.successors(x):A=this.neighbors(x),A.length===0},p.prototype.filterNodes=function(x){var A=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});A.setGraph(this.graph());var b=this;u.each(this._nodes,function(w,P){x(P)&&A.setNode(P,w)}),u.each(this._edgeObjs,function(w){A.hasNode(w.v)&&A.hasNode(w.w)&&A.setEdge(w,b.edge(w))});var C={};function T(w){var P=b.parent(w);return P===void 0||A.hasNode(P)?(C[w]=P,P):P in C?C[P]:T(P)}return this._isCompound&&u.each(A.nodes(),function(w){A.setParent(w,T(w))}),A},p.prototype.setDefaultEdgeLabel=function(x){return u.isFunction(x)||(x=u.constant(x)),this._defaultEdgeLabelFn=x,this},p.prototype.edgeCount=function(){return this._edgeCount},p.prototype.edges=function(){return u.values(this._edgeObjs)},p.prototype.setPath=function(x,A){var b=this,C=arguments;return u.reduce(x,function(T,w){return C.length>1?b.setEdge(T,w,A):b.setEdge(T,w),w}),this},p.prototype.setEdge=function(){var x,A,b,C,T=!1,w=arguments[0];typeof w=="object"&&w!==null&&"v"in w?(x=w.v,A=w.w,b=w.name,arguments.length===2&&(C=arguments[1],T=!0)):(x=w,A=arguments[1],b=arguments[3],arguments.length>2&&(C=arguments[2],T=!0)),x=""+x,A=""+A,u.isUndefined(b)||(b=""+b);var P=_(this._isDirected,x,A,b);if(u.has(this._edgeLabels,P))return T&&(this._edgeLabels[P]=C),this;if(!u.isUndefined(b)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(x),this.setNode(A),this._edgeLabels[P]=T?C:this._defaultEdgeLabelFn(x,A,b);var M=y(this._isDirected,x,A,b);return x=M.v,A=M.w,Object.freeze(M),this._edgeObjs[P]=M,m(this._preds[A],x),m(this._sucs[x],A),this._in[A][P]=M,this._out[x][P]=M,this._edgeCount++,this},p.prototype.edge=function(x,A,b){var C=arguments.length===1?v(this._isDirected,arguments[0]):_(this._isDirected,x,A,b);return this._edgeLabels[C]},p.prototype.hasEdge=function(x,A,b){var C=arguments.length===1?v(this._isDirected,arguments[0]):_(this._isDirected,x,A,b);return u.has(this._edgeLabels,C)},p.prototype.removeEdge=function(x,A,b){var C=arguments.length===1?v(this._isDirected,arguments[0]):_(this._isDirected,x,A,b),T=this._edgeObjs[C];return T&&(x=T.v,A=T.w,delete this._edgeLabels[C],delete this._edgeObjs[C],g(this._preds[A],x),g(this._sucs[x],A),delete this._in[A][C],delete this._out[x][C],this._edgeCount--),this},p.prototype.inEdges=function(x,A){var b=this._in[x];if(b){var C=u.values(b);return A?u.filter(C,function(T){return T.v===A}):C}},p.prototype.outEdges=function(x,A){var b=this._out[x];if(b){var C=u.values(b);return A?u.filter(C,function(T){return T.w===A}):C}},p.prototype.nodeEdges=function(x,A){var b=this.inEdges(x,A);if(b)return b.concat(this.outEdges(x,A))};function m(x,A){x[A]?x[A]++:x[A]=1}function g(x,A){--x[A]||delete x[A]}function _(x,A,b,C){var T=""+A,w=""+b;if(!x&&T>w){var P=T;T=w,w=P}return T+f+w+f+(u.isUndefined(C)?h:C)}function y(x,A,b,C){var T=""+A,w=""+b;if(!x&&T>w){var P=T;T=w,w=P}var M={v:T,w};return C&&(M.name=C),M}function v(x,A){return _(x,A.v,A.w,A.name)}},"../../../../node_modules/graphlib/lib/index.js":(o,l,c)=>{o.exports={Graph:c("../../../../node_modules/graphlib/lib/graph.js"),version:c("../../../../node_modules/graphlib/lib/version.js")}},"../../../../node_modules/graphlib/lib/json.js":(o,l,c)=>{var u=c("../../../../node_modules/graphlib/lib/lodash.js"),h=c("../../../../node_modules/graphlib/lib/graph.js");o.exports={write:d,read:m};function d(g){var _={options:{directed:g.isDirected(),multigraph:g.isMultigraph(),compound:g.isCompound()},nodes:f(g),edges:p(g)};return u.isUndefined(g.graph())||(_.value=u.clone(g.graph())),_}function f(g){return u.map(g.nodes(),function(_){var y=g.node(_),v=g.parent(_),x={v:_};return u.isUndefined(y)||(x.value=y),u.isUndefined(v)||(x.parent=v),x})}function p(g){return u.map(g.edges(),function(_){var y=g.edge(_),v={v:_.v,w:_.w};return u.isUndefined(_.name)||(v.name=_.name),u.isUndefined(y)||(v.value=y),v})}function m(g){var _=new h(g.options).setGraph(g.value);return u.each(g.nodes,function(y){_.setNode(y.v,y.value),y.parent&&_.setParent(y.v,y.parent)}),u.each(g.edges,function(y){_.setEdge({v:y.v,w:y.w,name:y.name},y.value)}),_}},"../../../../node_modules/graphlib/lib/lodash.js":(o,l,c)=>{var u;try{u={clone:c("../../../../node_modules/lodash/clone.js"),constant:c("../../../../node_modules/lodash/constant.js"),each:c("../../../../node_modules/lodash/each.js"),filter:c("../../../../node_modules/lodash/filter.js"),has:c("../../../../node_modules/lodash/has.js"),isArray:c("../../../../node_modules/lodash/isArray.js"),isEmpty:c("../../../../node_modules/lodash/isEmpty.js"),isFunction:c("../../../../node_modules/lodash/isFunction.js"),isUndefined:c("../../../../node_modules/lodash/isUndefined.js"),keys:c("../../../../node_modules/lodash/keys.js"),map:c("../../../../node_modules/lodash/map.js"),reduce:c("../../../../node_modules/lodash/reduce.js"),size:c("../../../../node_modules/lodash/size.js"),transform:c("../../../../node_modules/lodash/transform.js"),union:c("../../../../node_modules/lodash/union.js"),values:c("../../../../node_modules/lodash/values.js")}}catch{}u||(u=window._),o.exports=u},"../../../../node_modules/graphlib/lib/version.js":o=>{o.exports="2.1.8"},"../../../../node_modules/lodash/_DataView.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getNative.js"),h=c("../../../../node_modules/lodash/_root.js"),d=u(h,"DataView");o.exports=d},"../../../../node_modules/lodash/_Hash.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_hashClear.js"),h=c("../../../../node_modules/lodash/_hashDelete.js"),d=c("../../../../node_modules/lodash/_hashGet.js"),f=c("../../../../node_modules/lodash/_hashHas.js"),p=c("../../../../node_modules/lodash/_hashSet.js");function m(g){var _=-1,y=g==null?0:g.length;for(this.clear();++_{var u=c("../../../../node_modules/lodash/_listCacheClear.js"),h=c("../../../../node_modules/lodash/_listCacheDelete.js"),d=c("../../../../node_modules/lodash/_listCacheGet.js"),f=c("../../../../node_modules/lodash/_listCacheHas.js"),p=c("../../../../node_modules/lodash/_listCacheSet.js");function m(g){var _=-1,y=g==null?0:g.length;for(this.clear();++_{var u=c("../../../../node_modules/lodash/_getNative.js"),h=c("../../../../node_modules/lodash/_root.js"),d=u(h,"Map");o.exports=d},"../../../../node_modules/lodash/_MapCache.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_mapCacheClear.js"),h=c("../../../../node_modules/lodash/_mapCacheDelete.js"),d=c("../../../../node_modules/lodash/_mapCacheGet.js"),f=c("../../../../node_modules/lodash/_mapCacheHas.js"),p=c("../../../../node_modules/lodash/_mapCacheSet.js");function m(g){var _=-1,y=g==null?0:g.length;for(this.clear();++_{var u=c("../../../../node_modules/lodash/_getNative.js"),h=c("../../../../node_modules/lodash/_root.js"),d=u(h,"Promise");o.exports=d},"../../../../node_modules/lodash/_Set.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getNative.js"),h=c("../../../../node_modules/lodash/_root.js"),d=u(h,"Set");o.exports=d},"../../../../node_modules/lodash/_SetCache.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_MapCache.js"),h=c("../../../../node_modules/lodash/_setCacheAdd.js"),d=c("../../../../node_modules/lodash/_setCacheHas.js");function f(p){var m=-1,g=p==null?0:p.length;for(this.__data__=new u;++m{var u=c("../../../../node_modules/lodash/_ListCache.js"),h=c("../../../../node_modules/lodash/_stackClear.js"),d=c("../../../../node_modules/lodash/_stackDelete.js"),f=c("../../../../node_modules/lodash/_stackGet.js"),p=c("../../../../node_modules/lodash/_stackHas.js"),m=c("../../../../node_modules/lodash/_stackSet.js");function g(_){var y=this.__data__=new u(_);this.size=y.size}g.prototype.clear=h,g.prototype.delete=d,g.prototype.get=f,g.prototype.has=p,g.prototype.set=m,o.exports=g},"../../../../node_modules/lodash/_Symbol.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_root.js"),h=u.Symbol;o.exports=h},"../../../../node_modules/lodash/_Uint8Array.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_root.js"),h=u.Uint8Array;o.exports=h},"../../../../node_modules/lodash/_WeakMap.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getNative.js"),h=c("../../../../node_modules/lodash/_root.js"),d=u(h,"WeakMap");o.exports=d},"../../../../node_modules/lodash/_apply.js":o=>{function l(c,u,h){switch(h.length){case 0:return c.call(u);case 1:return c.call(u,h[0]);case 2:return c.call(u,h[0],h[1]);case 3:return c.call(u,h[0],h[1],h[2])}return c.apply(u,h)}o.exports=l},"../../../../node_modules/lodash/_arrayEach.js":o=>{function l(c,u){for(var h=-1,d=c==null?0:c.length;++h{function l(c,u){for(var h=-1,d=c==null?0:c.length,f=0,p=[];++h{var u=c("../../../../node_modules/lodash/_baseIndexOf.js");function h(d,f){var p=d==null?0:d.length;return!!p&&u(d,f,0)>-1}o.exports=h},"../../../../node_modules/lodash/_arrayIncludesWith.js":o=>{function l(c,u,h){for(var d=-1,f=c==null?0:c.length;++d{var u=c("../../../../node_modules/lodash/_baseTimes.js"),h=c("../../../../node_modules/lodash/isArguments.js"),d=c("../../../../node_modules/lodash/isArray.js"),f=c("../../../../node_modules/lodash/isBuffer.js"),p=c("../../../../node_modules/lodash/_isIndex.js"),m=c("../../../../node_modules/lodash/isTypedArray.js"),g=Object.prototype,_=g.hasOwnProperty;function y(v,x){var A=d(v),b=!A&&h(v),C=!A&&!b&&f(v),T=!A&&!b&&!C&&m(v),w=A||b||C||T,P=w?u(v.length,String):[],M=P.length;for(var R in v)(x||_.call(v,R))&&!(w&&(R=="length"||C&&(R=="offset"||R=="parent")||T&&(R=="buffer"||R=="byteLength"||R=="byteOffset")||p(R,M)))&&P.push(R);return P}o.exports=y},"../../../../node_modules/lodash/_arrayMap.js":o=>{function l(c,u){for(var h=-1,d=c==null?0:c.length,f=Array(d);++h{function l(c,u){for(var h=-1,d=u.length,f=c.length;++h{function l(c,u,h,d){var f=-1,p=c==null?0:c.length;for(d&&p&&(h=c[++f]);++f{function l(c,u){for(var h=-1,d=c==null?0:c.length;++h{var u=c("../../../../node_modules/lodash/_baseProperty.js"),h=u("length");o.exports=h},"../../../../node_modules/lodash/_assignMergeValue.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseAssignValue.js"),h=c("../../../../node_modules/lodash/eq.js");function d(f,p,m){(m!==void 0&&!h(f[p],m)||m===void 0&&!(p in f))&&u(f,p,m)}o.exports=d},"../../../../node_modules/lodash/_assignValue.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseAssignValue.js"),h=c("../../../../node_modules/lodash/eq.js"),d=Object.prototype,f=d.hasOwnProperty;function p(m,g,_){var y=m[g];(!(f.call(m,g)&&h(y,_))||_===void 0&&!(g in m))&&u(m,g,_)}o.exports=p},"../../../../node_modules/lodash/_assocIndexOf.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/eq.js");function h(d,f){for(var p=d.length;p--;)if(u(d[p][0],f))return p;return-1}o.exports=h},"../../../../node_modules/lodash/_baseAssign.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_copyObject.js"),h=c("../../../../node_modules/lodash/keys.js");function d(f,p){return f&&u(p,h(p),f)}o.exports=d},"../../../../node_modules/lodash/_baseAssignIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_copyObject.js"),h=c("../../../../node_modules/lodash/keysIn.js");function d(f,p){return f&&u(p,h(p),f)}o.exports=d},"../../../../node_modules/lodash/_baseAssignValue.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_defineProperty.js");function h(d,f,p){f=="__proto__"&&u?u(d,f,{configurable:!0,enumerable:!0,value:p,writable:!0}):d[f]=p}o.exports=h},"../../../../node_modules/lodash/_baseClone.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Stack.js"),h=c("../../../../node_modules/lodash/_arrayEach.js"),d=c("../../../../node_modules/lodash/_assignValue.js"),f=c("../../../../node_modules/lodash/_baseAssign.js"),p=c("../../../../node_modules/lodash/_baseAssignIn.js"),m=c("../../../../node_modules/lodash/_cloneBuffer.js"),g=c("../../../../node_modules/lodash/_copyArray.js"),_=c("../../../../node_modules/lodash/_copySymbols.js"),y=c("../../../../node_modules/lodash/_copySymbolsIn.js"),v=c("../../../../node_modules/lodash/_getAllKeys.js"),x=c("../../../../node_modules/lodash/_getAllKeysIn.js"),A=c("../../../../node_modules/lodash/_getTag.js"),b=c("../../../../node_modules/lodash/_initCloneArray.js"),C=c("../../../../node_modules/lodash/_initCloneByTag.js"),T=c("../../../../node_modules/lodash/_initCloneObject.js"),w=c("../../../../node_modules/lodash/isArray.js"),P=c("../../../../node_modules/lodash/isBuffer.js"),M=c("../../../../node_modules/lodash/isMap.js"),R=c("../../../../node_modules/lodash/isObject.js"),I=c("../../../../node_modules/lodash/isSet.js"),L=c("../../../../node_modules/lodash/keys.js"),k=c("../../../../node_modules/lodash/keysIn.js"),V=1,H=2,j=4,z="[object Arguments]",K="[object Array]",U="[object Boolean]",W="[object Date]",Z="[object Error]",q="[object Function]",ie="[object GeneratorFunction]",ae="[object Map]",ue="[object Number]",ce="[object Object]",N="[object RegExp]",B="[object Set]",Y="[object String]",te="[object Symbol]",oe="[object WeakMap]",ne="[object ArrayBuffer]",pe="[object DataView]",ye="[object Float32Array]",Ie="[object Float64Array]",Ne="[object Int8Array]",Ve="[object Int16Array]",nt="[object Int32Array]",Ke="[object Uint8Array]",Et="[object Uint8ClampedArray]",ft="[object Uint16Array]",Tt="[object Uint32Array]",Zt={};Zt[z]=Zt[K]=Zt[ne]=Zt[pe]=Zt[U]=Zt[W]=Zt[ye]=Zt[Ie]=Zt[Ne]=Zt[Ve]=Zt[nt]=Zt[ae]=Zt[ue]=Zt[ce]=Zt[N]=Zt[B]=Zt[Y]=Zt[te]=Zt[Ke]=Zt[Et]=Zt[ft]=Zt[Tt]=!0,Zt[Z]=Zt[q]=Zt[oe]=!1;function Ji(hi,hr,tr,Jr,Ti,Yi){var Si,dr=hr&V,Hi=hr&H,er=hr&j;if(tr&&(Si=Ti?tr(hi,Jr,Ti,Yi):tr(hi)),Si!==void 0)return Si;if(!R(hi))return hi;var rr=w(hi);if(rr){if(Si=b(hi),!dr)return g(hi,Si)}else{var Dr=A(hi),Wt=Dr==q||Dr==ie;if(P(hi))return m(hi,dr);if(Dr==ce||Dr==z||Wt&&!Ti){if(Si=Hi||Wt?{}:T(hi),!dr)return Hi?y(hi,p(Si,hi)):_(hi,f(Si,hi))}else{if(!Zt[Dr])return Ti?hi:{};Si=C(hi,Dr,dr)}}Yi||(Yi=new u);var ni=Yi.get(hi);if(ni)return ni;Yi.set(hi,Si),I(hi)?hi.forEach(function(ar){Si.add(Ji(ar,hr,tr,ar,hi,Yi))}):M(hi)&&hi.forEach(function(ar,Cr){Si.set(Cr,Ji(ar,hr,tr,Cr,hi,Yi))});var Yt=er?Hi?x:v:Hi?k:L,Ni=rr?void 0:Yt(hi);return h(Ni||hi,function(ar,Cr){Ni&&(Cr=ar,ar=hi[Cr]),d(Si,Cr,Ji(ar,hr,tr,Cr,hi,Yi))}),Si}o.exports=Ji},"../../../../node_modules/lodash/_baseCreate.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isObject.js"),h=Object.create,d=function(){function f(){}return function(p){if(!u(p))return{};if(h)return h(p);f.prototype=p;var m=new f;return f.prototype=void 0,m}}();o.exports=d},"../../../../node_modules/lodash/_baseEach.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseForOwn.js"),h=c("../../../../node_modules/lodash/_createBaseEach.js"),d=h(u);o.exports=d},"../../../../node_modules/lodash/_baseExtremum.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isSymbol.js");function h(d,f,p){for(var m=-1,g=d.length;++m{var u=c("../../../../node_modules/lodash/_baseEach.js");function h(d,f){var p=[];return u(d,function(m,g,_){f(m,g,_)&&p.push(m)}),p}o.exports=h},"../../../../node_modules/lodash/_baseFindIndex.js":o=>{function l(c,u,h,d){for(var f=c.length,p=h+(d?1:-1);d?p--:++p{var u=c("../../../../node_modules/lodash/_arrayPush.js"),h=c("../../../../node_modules/lodash/_isFlattenable.js");function d(f,p,m,g,_){var y=-1,v=f.length;for(m||(m=h),_||(_=[]);++y0&&m(x)?p>1?d(x,p-1,m,g,_):u(_,x):g||(_[_.length]=x)}return _}o.exports=d},"../../../../node_modules/lodash/_baseFor.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_createBaseFor.js"),h=u();o.exports=h},"../../../../node_modules/lodash/_baseForOwn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFor.js"),h=c("../../../../node_modules/lodash/keys.js");function d(f,p){return f&&u(f,p,h)}o.exports=d},"../../../../node_modules/lodash/_baseGet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_castPath.js"),h=c("../../../../node_modules/lodash/_toKey.js");function d(f,p){p=u(p,f);for(var m=0,g=p.length;f!=null&&m{var u=c("../../../../node_modules/lodash/_arrayPush.js"),h=c("../../../../node_modules/lodash/isArray.js");function d(f,p,m){var g=p(f);return h(f)?g:u(g,m(f))}o.exports=d},"../../../../node_modules/lodash/_baseGetTag.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Symbol.js"),h=c("../../../../node_modules/lodash/_getRawTag.js"),d=c("../../../../node_modules/lodash/_objectToString.js"),f="[object Null]",p="[object Undefined]",m=u?u.toStringTag:void 0;function g(_){return _==null?_===void 0?p:f:m&&m in Object(_)?h(_):d(_)}o.exports=g},"../../../../node_modules/lodash/_baseGt.js":o=>{function l(c,u){return c>u}o.exports=l},"../../../../node_modules/lodash/_baseHas.js":o=>{var l=Object.prototype,c=l.hasOwnProperty;function u(h,d){return h!=null&&c.call(h,d)}o.exports=u},"../../../../node_modules/lodash/_baseHasIn.js":o=>{function l(c,u){return c!=null&&u in Object(c)}o.exports=l},"../../../../node_modules/lodash/_baseIndexOf.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFindIndex.js"),h=c("../../../../node_modules/lodash/_baseIsNaN.js"),d=c("../../../../node_modules/lodash/_strictIndexOf.js");function f(p,m,g){return m===m?d(p,m,g):u(p,h,g)}o.exports=f},"../../../../node_modules/lodash/_baseIsArguments.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetTag.js"),h=c("../../../../node_modules/lodash/isObjectLike.js"),d="[object Arguments]";function f(p){return h(p)&&u(p)==d}o.exports=f},"../../../../node_modules/lodash/_baseIsEqual.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsEqualDeep.js"),h=c("../../../../node_modules/lodash/isObjectLike.js");function d(f,p,m,g,_){return f===p?!0:f==null||p==null||!h(f)&&!h(p)?f!==f&&p!==p:u(f,p,m,g,d,_)}o.exports=d},"../../../../node_modules/lodash/_baseIsEqualDeep.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Stack.js"),h=c("../../../../node_modules/lodash/_equalArrays.js"),d=c("../../../../node_modules/lodash/_equalByTag.js"),f=c("../../../../node_modules/lodash/_equalObjects.js"),p=c("../../../../node_modules/lodash/_getTag.js"),m=c("../../../../node_modules/lodash/isArray.js"),g=c("../../../../node_modules/lodash/isBuffer.js"),_=c("../../../../node_modules/lodash/isTypedArray.js"),y=1,v="[object Arguments]",x="[object Array]",A="[object Object]",b=Object.prototype,C=b.hasOwnProperty;function T(w,P,M,R,I,L){var k=m(w),V=m(P),H=k?x:p(w),j=V?x:p(P);H=H==v?A:H,j=j==v?A:j;var z=H==A,K=j==A,U=H==j;if(U&&g(w)){if(!g(P))return!1;k=!0,z=!1}if(U&&!z)return L||(L=new u),k||_(w)?h(w,P,M,R,I,L):d(w,P,H,M,R,I,L);if(!(M&y)){var W=z&&C.call(w,"__wrapped__"),Z=K&&C.call(P,"__wrapped__");if(W||Z){var q=W?w.value():w,ie=Z?P.value():P;return L||(L=new u),I(q,ie,M,R,L)}}return U?(L||(L=new u),f(w,P,M,R,I,L)):!1}o.exports=T},"../../../../node_modules/lodash/_baseIsMap.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getTag.js"),h=c("../../../../node_modules/lodash/isObjectLike.js"),d="[object Map]";function f(p){return h(p)&&u(p)==d}o.exports=f},"../../../../node_modules/lodash/_baseIsMatch.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Stack.js"),h=c("../../../../node_modules/lodash/_baseIsEqual.js"),d=1,f=2;function p(m,g,_,y){var v=_.length,x=v,A=!y;if(m==null)return!x;for(m=Object(m);v--;){var b=_[v];if(A&&b[2]?b[1]!==m[b[0]]:!(b[0]in m))return!1}for(;++v{function l(c){return c!==c}o.exports=l},"../../../../node_modules/lodash/_baseIsNative.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isFunction.js"),h=c("../../../../node_modules/lodash/_isMasked.js"),d=c("../../../../node_modules/lodash/isObject.js"),f=c("../../../../node_modules/lodash/_toSource.js"),p=/[\\^$.*+?()[\]{}|]/g,m=/^\[object .+?Constructor\]$/,g=Function.prototype,_=Object.prototype,y=g.toString,v=_.hasOwnProperty,x=RegExp("^"+y.call(v).replace(p,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function A(b){if(!d(b)||h(b))return!1;var C=u(b)?x:m;return C.test(f(b))}o.exports=A},"../../../../node_modules/lodash/_baseIsSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getTag.js"),h=c("../../../../node_modules/lodash/isObjectLike.js"),d="[object Set]";function f(p){return h(p)&&u(p)==d}o.exports=f},"../../../../node_modules/lodash/_baseIsTypedArray.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetTag.js"),h=c("../../../../node_modules/lodash/isLength.js"),d=c("../../../../node_modules/lodash/isObjectLike.js"),f="[object Arguments]",p="[object Array]",m="[object Boolean]",g="[object Date]",_="[object Error]",y="[object Function]",v="[object Map]",x="[object Number]",A="[object Object]",b="[object RegExp]",C="[object Set]",T="[object String]",w="[object WeakMap]",P="[object ArrayBuffer]",M="[object DataView]",R="[object Float32Array]",I="[object Float64Array]",L="[object Int8Array]",k="[object Int16Array]",V="[object Int32Array]",H="[object Uint8Array]",j="[object Uint8ClampedArray]",z="[object Uint16Array]",K="[object Uint32Array]",U={};U[R]=U[I]=U[L]=U[k]=U[V]=U[H]=U[j]=U[z]=U[K]=!0,U[f]=U[p]=U[P]=U[m]=U[M]=U[g]=U[_]=U[y]=U[v]=U[x]=U[A]=U[b]=U[C]=U[T]=U[w]=!1;function W(Z){return d(Z)&&h(Z.length)&&!!U[u(Z)]}o.exports=W},"../../../../node_modules/lodash/_baseIteratee.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseMatches.js"),h=c("../../../../node_modules/lodash/_baseMatchesProperty.js"),d=c("../../../../node_modules/lodash/identity.js"),f=c("../../../../node_modules/lodash/isArray.js"),p=c("../../../../node_modules/lodash/property.js");function m(g){return typeof g=="function"?g:g==null?d:typeof g=="object"?f(g)?h(g[0],g[1]):u(g):p(g)}o.exports=m},"../../../../node_modules/lodash/_baseKeys.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_isPrototype.js"),h=c("../../../../node_modules/lodash/_nativeKeys.js"),d=Object.prototype,f=d.hasOwnProperty;function p(m){if(!u(m))return h(m);var g=[];for(var _ in Object(m))f.call(m,_)&&_!="constructor"&&g.push(_);return g}o.exports=p},"../../../../node_modules/lodash/_baseKeysIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isObject.js"),h=c("../../../../node_modules/lodash/_isPrototype.js"),d=c("../../../../node_modules/lodash/_nativeKeysIn.js"),f=Object.prototype,p=f.hasOwnProperty;function m(g){if(!u(g))return d(g);var _=h(g),y=[];for(var v in g)v=="constructor"&&(_||!p.call(g,v))||y.push(v);return y}o.exports=m},"../../../../node_modules/lodash/_baseLt.js":o=>{function l(c,u){return c{var u=c("../../../../node_modules/lodash/_baseEach.js"),h=c("../../../../node_modules/lodash/isArrayLike.js");function d(f,p){var m=-1,g=h(f)?Array(f.length):[];return u(f,function(_,y,v){g[++m]=p(_,y,v)}),g}o.exports=d},"../../../../node_modules/lodash/_baseMatches.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsMatch.js"),h=c("../../../../node_modules/lodash/_getMatchData.js"),d=c("../../../../node_modules/lodash/_matchesStrictComparable.js");function f(p){var m=h(p);return m.length==1&&m[0][2]?d(m[0][0],m[0][1]):function(g){return g===p||u(g,p,m)}}o.exports=f},"../../../../node_modules/lodash/_baseMatchesProperty.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsEqual.js"),h=c("../../../../node_modules/lodash/get.js"),d=c("../../../../node_modules/lodash/hasIn.js"),f=c("../../../../node_modules/lodash/_isKey.js"),p=c("../../../../node_modules/lodash/_isStrictComparable.js"),m=c("../../../../node_modules/lodash/_matchesStrictComparable.js"),g=c("../../../../node_modules/lodash/_toKey.js"),_=1,y=2;function v(x,A){return f(x)&&p(A)?m(g(x),A):function(b){var C=h(b,x);return C===void 0&&C===A?d(b,x):u(A,C,_|y)}}o.exports=v},"../../../../node_modules/lodash/_baseMerge.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Stack.js"),h=c("../../../../node_modules/lodash/_assignMergeValue.js"),d=c("../../../../node_modules/lodash/_baseFor.js"),f=c("../../../../node_modules/lodash/_baseMergeDeep.js"),p=c("../../../../node_modules/lodash/isObject.js"),m=c("../../../../node_modules/lodash/keysIn.js"),g=c("../../../../node_modules/lodash/_safeGet.js");function _(y,v,x,A,b){y!==v&&d(v,function(C,T){if(b||(b=new u),p(C))f(y,v,T,x,_,A,b);else{var w=A?A(g(y,T),C,T+"",y,v,b):void 0;w===void 0&&(w=C),h(y,T,w)}},m)}o.exports=_},"../../../../node_modules/lodash/_baseMergeDeep.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assignMergeValue.js"),h=c("../../../../node_modules/lodash/_cloneBuffer.js"),d=c("../../../../node_modules/lodash/_cloneTypedArray.js"),f=c("../../../../node_modules/lodash/_copyArray.js"),p=c("../../../../node_modules/lodash/_initCloneObject.js"),m=c("../../../../node_modules/lodash/isArguments.js"),g=c("../../../../node_modules/lodash/isArray.js"),_=c("../../../../node_modules/lodash/isArrayLikeObject.js"),y=c("../../../../node_modules/lodash/isBuffer.js"),v=c("../../../../node_modules/lodash/isFunction.js"),x=c("../../../../node_modules/lodash/isObject.js"),A=c("../../../../node_modules/lodash/isPlainObject.js"),b=c("../../../../node_modules/lodash/isTypedArray.js"),C=c("../../../../node_modules/lodash/_safeGet.js"),T=c("../../../../node_modules/lodash/toPlainObject.js");function w(P,M,R,I,L,k,V){var H=C(P,R),j=C(M,R),z=V.get(j);if(z){u(P,R,z);return}var K=k?k(H,j,R+"",P,M,V):void 0,U=K===void 0;if(U){var W=g(j),Z=!W&&y(j),q=!W&&!Z&&b(j);K=j,W||Z||q?g(H)?K=H:_(H)?K=f(H):Z?(U=!1,K=h(j,!0)):q?(U=!1,K=d(j,!0)):K=[]:A(j)||m(j)?(K=H,m(H)?K=T(H):(!x(H)||v(H))&&(K=p(j))):U=!1}U&&(V.set(j,K),L(K,j,I,k,V),V.delete(j)),u(P,R,K)}o.exports=w},"../../../../node_modules/lodash/_baseOrderBy.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayMap.js"),h=c("../../../../node_modules/lodash/_baseGet.js"),d=c("../../../../node_modules/lodash/_baseIteratee.js"),f=c("../../../../node_modules/lodash/_baseMap.js"),p=c("../../../../node_modules/lodash/_baseSortBy.js"),m=c("../../../../node_modules/lodash/_baseUnary.js"),g=c("../../../../node_modules/lodash/_compareMultiple.js"),_=c("../../../../node_modules/lodash/identity.js"),y=c("../../../../node_modules/lodash/isArray.js");function v(x,A,b){A.length?A=u(A,function(w){return y(w)?function(P){return h(P,w.length===1?w[0]:w)}:w}):A=[_];var C=-1;A=u(A,m(d));var T=f(x,function(w,P,M){var R=u(A,function(I){return I(w)});return{criteria:R,index:++C,value:w}});return p(T,function(w,P){return g(w,P,b)})}o.exports=v},"../../../../node_modules/lodash/_basePick.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_basePickBy.js"),h=c("../../../../node_modules/lodash/hasIn.js");function d(f,p){return u(f,p,function(m,g){return h(f,g)})}o.exports=d},"../../../../node_modules/lodash/_basePickBy.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGet.js"),h=c("../../../../node_modules/lodash/_baseSet.js"),d=c("../../../../node_modules/lodash/_castPath.js");function f(p,m,g){for(var _=-1,y=m.length,v={};++_{function l(c){return function(u){return u==null?void 0:u[c]}}o.exports=l},"../../../../node_modules/lodash/_basePropertyDeep.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGet.js");function h(d){return function(f){return u(f,d)}}o.exports=h},"../../../../node_modules/lodash/_baseRange.js":o=>{var l=Math.ceil,c=Math.max;function u(h,d,f,p){for(var m=-1,g=c(l((d-h)/(f||1)),0),_=Array(g);g--;)_[p?g:++m]=h,h+=f;return _}o.exports=u},"../../../../node_modules/lodash/_baseReduce.js":o=>{function l(c,u,h,d,f){return f(c,function(p,m,g){h=d?(d=!1,p):u(h,p,m,g)}),h}o.exports=l},"../../../../node_modules/lodash/_baseRest.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/identity.js"),h=c("../../../../node_modules/lodash/_overRest.js"),d=c("../../../../node_modules/lodash/_setToString.js");function f(p,m){return d(h(p,m,u),p+"")}o.exports=f},"../../../../node_modules/lodash/_baseSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assignValue.js"),h=c("../../../../node_modules/lodash/_castPath.js"),d=c("../../../../node_modules/lodash/_isIndex.js"),f=c("../../../../node_modules/lodash/isObject.js"),p=c("../../../../node_modules/lodash/_toKey.js");function m(g,_,y,v){if(!f(g))return g;_=h(_,g);for(var x=-1,A=_.length,b=A-1,C=g;C!=null&&++x{var u=c("../../../../node_modules/lodash/constant.js"),h=c("../../../../node_modules/lodash/_defineProperty.js"),d=c("../../../../node_modules/lodash/identity.js"),f=h?function(p,m){return h(p,"toString",{configurable:!0,enumerable:!1,value:u(m),writable:!0})}:d;o.exports=f},"../../../../node_modules/lodash/_baseSortBy.js":o=>{function l(c,u){var h=c.length;for(c.sort(u);h--;)c[h]=c[h].value;return c}o.exports=l},"../../../../node_modules/lodash/_baseTimes.js":o=>{function l(c,u){for(var h=-1,d=Array(c);++h{var u=c("../../../../node_modules/lodash/_Symbol.js"),h=c("../../../../node_modules/lodash/_arrayMap.js"),d=c("../../../../node_modules/lodash/isArray.js"),f=c("../../../../node_modules/lodash/isSymbol.js"),p=1/0,m=u?u.prototype:void 0,g=m?m.toString:void 0;function _(y){if(typeof y=="string")return y;if(d(y))return h(y,_)+"";if(f(y))return g?g.call(y):"";var v=y+"";return v=="0"&&1/y==-p?"-0":v}o.exports=_},"../../../../node_modules/lodash/_baseTrim.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_trimmedEndIndex.js"),h=/^\s+/;function d(f){return f&&f.slice(0,u(f)+1).replace(h,"")}o.exports=d},"../../../../node_modules/lodash/_baseUnary.js":o=>{function l(c){return function(u){return c(u)}}o.exports=l},"../../../../node_modules/lodash/_baseUniq.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_SetCache.js"),h=c("../../../../node_modules/lodash/_arrayIncludes.js"),d=c("../../../../node_modules/lodash/_arrayIncludesWith.js"),f=c("../../../../node_modules/lodash/_cacheHas.js"),p=c("../../../../node_modules/lodash/_createSet.js"),m=c("../../../../node_modules/lodash/_setToArray.js"),g=200;function _(y,v,x){var A=-1,b=h,C=y.length,T=!0,w=[],P=w;if(x)T=!1,b=d;else if(C>=g){var M=v?null:p(y);if(M)return m(M);T=!1,b=f,P=new u}else P=v?[]:w;e:for(;++A{var u=c("../../../../node_modules/lodash/_arrayMap.js");function h(d,f){return u(f,function(p){return d[p]})}o.exports=h},"../../../../node_modules/lodash/_baseZipObject.js":o=>{function l(c,u,h){for(var d=-1,f=c.length,p=u.length,m={};++d{function l(c,u){return c.has(u)}o.exports=l},"../../../../node_modules/lodash/_castFunction.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/identity.js");function h(d){return typeof d=="function"?d:u}o.exports=h},"../../../../node_modules/lodash/_castPath.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isArray.js"),h=c("../../../../node_modules/lodash/_isKey.js"),d=c("../../../../node_modules/lodash/_stringToPath.js"),f=c("../../../../node_modules/lodash/toString.js");function p(m,g){return u(m)?m:h(m,g)?[m]:d(f(m))}o.exports=p},"../../../../node_modules/lodash/_cloneArrayBuffer.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Uint8Array.js");function h(d){var f=new d.constructor(d.byteLength);return new u(f).set(new u(d)),f}o.exports=h},"../../../../node_modules/lodash/_cloneBuffer.js":(o,l,c)=>{o=c.nmd(o);var u=c("../../../../node_modules/lodash/_root.js"),h=l&&!l.nodeType&&l,d=h&&!0&&o&&!o.nodeType&&o,f=d&&d.exports===h,p=f?u.Buffer:void 0,m=p?p.allocUnsafe:void 0;function g(_,y){if(y)return _.slice();var v=_.length,x=m?m(v):new _.constructor(v);return _.copy(x),x}o.exports=g},"../../../../node_modules/lodash/_cloneDataView.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_cloneArrayBuffer.js");function h(d,f){var p=f?u(d.buffer):d.buffer;return new d.constructor(p,d.byteOffset,d.byteLength)}o.exports=h},"../../../../node_modules/lodash/_cloneRegExp.js":o=>{var l=/\w*$/;function c(u){var h=new u.constructor(u.source,l.exec(u));return h.lastIndex=u.lastIndex,h}o.exports=c},"../../../../node_modules/lodash/_cloneSymbol.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Symbol.js"),h=u?u.prototype:void 0,d=h?h.valueOf:void 0;function f(p){return d?Object(d.call(p)):{}}o.exports=f},"../../../../node_modules/lodash/_cloneTypedArray.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_cloneArrayBuffer.js");function h(d,f){var p=f?u(d.buffer):d.buffer;return new d.constructor(p,d.byteOffset,d.length)}o.exports=h},"../../../../node_modules/lodash/_compareAscending.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isSymbol.js");function h(d,f){if(d!==f){var p=d!==void 0,m=d===null,g=d===d,_=u(d),y=f!==void 0,v=f===null,x=f===f,A=u(f);if(!v&&!A&&!_&&d>f||_&&y&&x&&!v&&!A||m&&y&&x||!p&&x||!g)return 1;if(!m&&!_&&!A&&d{var u=c("../../../../node_modules/lodash/_compareAscending.js");function h(d,f,p){for(var m=-1,g=d.criteria,_=f.criteria,y=g.length,v=p.length;++m=v)return x;var A=p[m];return x*(A=="desc"?-1:1)}}return d.index-f.index}o.exports=h},"../../../../node_modules/lodash/_copyArray.js":o=>{function l(c,u){var h=-1,d=c.length;for(u||(u=Array(d));++h{var u=c("../../../../node_modules/lodash/_assignValue.js"),h=c("../../../../node_modules/lodash/_baseAssignValue.js");function d(f,p,m,g){var _=!m;m||(m={});for(var y=-1,v=p.length;++y{var u=c("../../../../node_modules/lodash/_copyObject.js"),h=c("../../../../node_modules/lodash/_getSymbols.js");function d(f,p){return u(f,h(f),p)}o.exports=d},"../../../../node_modules/lodash/_copySymbolsIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_copyObject.js"),h=c("../../../../node_modules/lodash/_getSymbolsIn.js");function d(f,p){return u(f,h(f),p)}o.exports=d},"../../../../node_modules/lodash/_coreJsData.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_root.js"),h=u["__core-js_shared__"];o.exports=h},"../../../../node_modules/lodash/_createAssigner.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseRest.js"),h=c("../../../../node_modules/lodash/_isIterateeCall.js");function d(f){return u(function(p,m){var g=-1,_=m.length,y=_>1?m[_-1]:void 0,v=_>2?m[2]:void 0;for(y=f.length>3&&typeof y=="function"?(_--,y):void 0,v&&h(m[0],m[1],v)&&(y=_<3?void 0:y,_=1),p=Object(p);++g<_;){var x=m[g];x&&f(p,x,g,y)}return p})}o.exports=d},"../../../../node_modules/lodash/_createBaseEach.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isArrayLike.js");function h(d,f){return function(p,m){if(p==null)return p;if(!u(p))return d(p,m);for(var g=p.length,_=f?g:-1,y=Object(p);(f?_--:++_{function l(c){return function(u,h,d){for(var f=-1,p=Object(u),m=d(u),g=m.length;g--;){var _=m[c?g:++f];if(h(p[_],_,p)===!1)break}return u}}o.exports=l},"../../../../node_modules/lodash/_createFind.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIteratee.js"),h=c("../../../../node_modules/lodash/isArrayLike.js"),d=c("../../../../node_modules/lodash/keys.js");function f(p){return function(m,g,_){var y=Object(m);if(!h(m)){var v=u(g,3);m=d(m),g=function(A){return v(y[A],A,y)}}var x=p(m,g,_);return x>-1?y[v?m[x]:x]:void 0}}o.exports=f},"../../../../node_modules/lodash/_createRange.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseRange.js"),h=c("../../../../node_modules/lodash/_isIterateeCall.js"),d=c("../../../../node_modules/lodash/toFinite.js");function f(p){return function(m,g,_){return _&&typeof _!="number"&&h(m,g,_)&&(g=_=void 0),m=d(m),g===void 0?(g=m,m=0):g=d(g),_=_===void 0?m{var u=c("../../../../node_modules/lodash/_Set.js"),h=c("../../../../node_modules/lodash/noop.js"),d=c("../../../../node_modules/lodash/_setToArray.js"),f=1/0,p=u&&1/d(new u([,-0]))[1]==f?function(m){return new u(m)}:h;o.exports=p},"../../../../node_modules/lodash/_defineProperty.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getNative.js"),h=function(){try{var d=u(Object,"defineProperty");return d({},"",{}),d}catch{}}();o.exports=h},"../../../../node_modules/lodash/_equalArrays.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_SetCache.js"),h=c("../../../../node_modules/lodash/_arraySome.js"),d=c("../../../../node_modules/lodash/_cacheHas.js"),f=1,p=2;function m(g,_,y,v,x,A){var b=y&f,C=g.length,T=_.length;if(C!=T&&!(b&&T>C))return!1;var w=A.get(g),P=A.get(_);if(w&&P)return w==_&&P==g;var M=-1,R=!0,I=y&p?new u:void 0;for(A.set(g,_),A.set(_,g);++M{var u=c("../../../../node_modules/lodash/_Symbol.js"),h=c("../../../../node_modules/lodash/_Uint8Array.js"),d=c("../../../../node_modules/lodash/eq.js"),f=c("../../../../node_modules/lodash/_equalArrays.js"),p=c("../../../../node_modules/lodash/_mapToArray.js"),m=c("../../../../node_modules/lodash/_setToArray.js"),g=1,_=2,y="[object Boolean]",v="[object Date]",x="[object Error]",A="[object Map]",b="[object Number]",C="[object RegExp]",T="[object Set]",w="[object String]",P="[object Symbol]",M="[object ArrayBuffer]",R="[object DataView]",I=u?u.prototype:void 0,L=I?I.valueOf:void 0;function k(V,H,j,z,K,U,W){switch(j){case R:if(V.byteLength!=H.byteLength||V.byteOffset!=H.byteOffset)return!1;V=V.buffer,H=H.buffer;case M:return!(V.byteLength!=H.byteLength||!U(new h(V),new h(H)));case y:case v:case b:return d(+V,+H);case x:return V.name==H.name&&V.message==H.message;case C:case w:return V==H+"";case A:var Z=p;case T:var q=z&g;if(Z||(Z=m),V.size!=H.size&&!q)return!1;var ie=W.get(V);if(ie)return ie==H;z|=_,W.set(V,H);var ae=f(Z(V),Z(H),z,K,U,W);return W.delete(V),ae;case P:if(L)return L.call(V)==L.call(H)}return!1}o.exports=k},"../../../../node_modules/lodash/_equalObjects.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getAllKeys.js"),h=1,d=Object.prototype,f=d.hasOwnProperty;function p(m,g,_,y,v,x){var A=_&h,b=u(m),C=b.length,T=u(g),w=T.length;if(C!=w&&!A)return!1;for(var P=C;P--;){var M=b[P];if(!(A?M in g:f.call(g,M)))return!1}var R=x.get(m),I=x.get(g);if(R&&I)return R==g&&I==m;var L=!0;x.set(m,g),x.set(g,m);for(var k=A;++P{var u=c("../../../../node_modules/lodash/flatten.js"),h=c("../../../../node_modules/lodash/_overRest.js"),d=c("../../../../node_modules/lodash/_setToString.js");function f(p){return d(h(p,void 0,u),p+"")}o.exports=f},"../../../../node_modules/lodash/_freeGlobal.js":(o,l,c)=>{var u=typeof c.g=="object"&&c.g&&c.g.Object===Object&&c.g;o.exports=u},"../../../../node_modules/lodash/_getAllKeys.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetAllKeys.js"),h=c("../../../../node_modules/lodash/_getSymbols.js"),d=c("../../../../node_modules/lodash/keys.js");function f(p){return u(p,d,h)}o.exports=f},"../../../../node_modules/lodash/_getAllKeysIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetAllKeys.js"),h=c("../../../../node_modules/lodash/_getSymbolsIn.js"),d=c("../../../../node_modules/lodash/keysIn.js");function f(p){return u(p,d,h)}o.exports=f},"../../../../node_modules/lodash/_getMapData.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_isKeyable.js");function h(d,f){var p=d.__data__;return u(f)?p[typeof f=="string"?"string":"hash"]:p.map}o.exports=h},"../../../../node_modules/lodash/_getMatchData.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_isStrictComparable.js"),h=c("../../../../node_modules/lodash/keys.js");function d(f){for(var p=h(f),m=p.length;m--;){var g=p[m],_=f[g];p[m]=[g,_,u(_)]}return p}o.exports=d},"../../../../node_modules/lodash/_getNative.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsNative.js"),h=c("../../../../node_modules/lodash/_getValue.js");function d(f,p){var m=h(f,p);return u(m)?m:void 0}o.exports=d},"../../../../node_modules/lodash/_getPrototype.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_overArg.js"),h=u(Object.getPrototypeOf,Object);o.exports=h},"../../../../node_modules/lodash/_getRawTag.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Symbol.js"),h=Object.prototype,d=h.hasOwnProperty,f=h.toString,p=u?u.toStringTag:void 0;function m(g){var _=d.call(g,p),y=g[p];try{g[p]=void 0;var v=!0}catch{}var x=f.call(g);return v&&(_?g[p]=y:delete g[p]),x}o.exports=m},"../../../../node_modules/lodash/_getSymbols.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayFilter.js"),h=c("../../../../node_modules/lodash/stubArray.js"),d=Object.prototype,f=d.propertyIsEnumerable,p=Object.getOwnPropertySymbols,m=p?function(g){return g==null?[]:(g=Object(g),u(p(g),function(_){return f.call(g,_)}))}:h;o.exports=m},"../../../../node_modules/lodash/_getSymbolsIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayPush.js"),h=c("../../../../node_modules/lodash/_getPrototype.js"),d=c("../../../../node_modules/lodash/_getSymbols.js"),f=c("../../../../node_modules/lodash/stubArray.js"),p=Object.getOwnPropertySymbols,m=p?function(g){for(var _=[];g;)u(_,d(g)),g=h(g);return _}:f;o.exports=m},"../../../../node_modules/lodash/_getTag.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_DataView.js"),h=c("../../../../node_modules/lodash/_Map.js"),d=c("../../../../node_modules/lodash/_Promise.js"),f=c("../../../../node_modules/lodash/_Set.js"),p=c("../../../../node_modules/lodash/_WeakMap.js"),m=c("../../../../node_modules/lodash/_baseGetTag.js"),g=c("../../../../node_modules/lodash/_toSource.js"),_="[object Map]",y="[object Object]",v="[object Promise]",x="[object Set]",A="[object WeakMap]",b="[object DataView]",C=g(u),T=g(h),w=g(d),P=g(f),M=g(p),R=m;(u&&R(new u(new ArrayBuffer(1)))!=b||h&&R(new h)!=_||d&&R(d.resolve())!=v||f&&R(new f)!=x||p&&R(new p)!=A)&&(R=function(I){var L=m(I),k=L==y?I.constructor:void 0,V=k?g(k):"";if(V)switch(V){case C:return b;case T:return _;case w:return v;case P:return x;case M:return A}return L}),o.exports=R},"../../../../node_modules/lodash/_getValue.js":o=>{function l(c,u){return c==null?void 0:c[u]}o.exports=l},"../../../../node_modules/lodash/_hasPath.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_castPath.js"),h=c("../../../../node_modules/lodash/isArguments.js"),d=c("../../../../node_modules/lodash/isArray.js"),f=c("../../../../node_modules/lodash/_isIndex.js"),p=c("../../../../node_modules/lodash/isLength.js"),m=c("../../../../node_modules/lodash/_toKey.js");function g(_,y,v){y=u(y,_);for(var x=-1,A=y.length,b=!1;++x{var l="\\ud800-\\udfff",c="\\u0300-\\u036f",u="\\ufe20-\\ufe2f",h="\\u20d0-\\u20ff",d=c+u+h,f="\\ufe0e\\ufe0f",p="\\u200d",m=RegExp("["+p+l+d+f+"]");function g(_){return m.test(_)}o.exports=g},"../../../../node_modules/lodash/_hashClear.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_nativeCreate.js");function h(){this.__data__=u?u(null):{},this.size=0}o.exports=h},"../../../../node_modules/lodash/_hashDelete.js":o=>{function l(c){var u=this.has(c)&&delete this.__data__[c];return this.size-=u?1:0,u}o.exports=l},"../../../../node_modules/lodash/_hashGet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_nativeCreate.js"),h="__lodash_hash_undefined__",d=Object.prototype,f=d.hasOwnProperty;function p(m){var g=this.__data__;if(u){var _=g[m];return _===h?void 0:_}return f.call(g,m)?g[m]:void 0}o.exports=p},"../../../../node_modules/lodash/_hashHas.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_nativeCreate.js"),h=Object.prototype,d=h.hasOwnProperty;function f(p){var m=this.__data__;return u?m[p]!==void 0:d.call(m,p)}o.exports=f},"../../../../node_modules/lodash/_hashSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_nativeCreate.js"),h="__lodash_hash_undefined__";function d(f,p){var m=this.__data__;return this.size+=this.has(f)?0:1,m[f]=u&&p===void 0?h:p,this}o.exports=d},"../../../../node_modules/lodash/_initCloneArray.js":o=>{var l=Object.prototype,c=l.hasOwnProperty;function u(h){var d=h.length,f=new h.constructor(d);return d&&typeof h[0]=="string"&&c.call(h,"index")&&(f.index=h.index,f.input=h.input),f}o.exports=u},"../../../../node_modules/lodash/_initCloneByTag.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_cloneArrayBuffer.js"),h=c("../../../../node_modules/lodash/_cloneDataView.js"),d=c("../../../../node_modules/lodash/_cloneRegExp.js"),f=c("../../../../node_modules/lodash/_cloneSymbol.js"),p=c("../../../../node_modules/lodash/_cloneTypedArray.js"),m="[object Boolean]",g="[object Date]",_="[object Map]",y="[object Number]",v="[object RegExp]",x="[object Set]",A="[object String]",b="[object Symbol]",C="[object ArrayBuffer]",T="[object DataView]",w="[object Float32Array]",P="[object Float64Array]",M="[object Int8Array]",R="[object Int16Array]",I="[object Int32Array]",L="[object Uint8Array]",k="[object Uint8ClampedArray]",V="[object Uint16Array]",H="[object Uint32Array]";function j(z,K,U){var W=z.constructor;switch(K){case C:return u(z);case m:case g:return new W(+z);case T:return h(z,U);case w:case P:case M:case R:case I:case L:case k:case V:case H:return p(z,U);case _:return new W;case y:case A:return new W(z);case v:return d(z);case x:return new W;case b:return f(z)}}o.exports=j},"../../../../node_modules/lodash/_initCloneObject.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseCreate.js"),h=c("../../../../node_modules/lodash/_getPrototype.js"),d=c("../../../../node_modules/lodash/_isPrototype.js");function f(p){return typeof p.constructor=="function"&&!d(p)?u(h(p)):{}}o.exports=f},"../../../../node_modules/lodash/_isFlattenable.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Symbol.js"),h=c("../../../../node_modules/lodash/isArguments.js"),d=c("../../../../node_modules/lodash/isArray.js"),f=u?u.isConcatSpreadable:void 0;function p(m){return d(m)||h(m)||!!(f&&m&&m[f])}o.exports=p},"../../../../node_modules/lodash/_isIndex.js":o=>{var l=9007199254740991,c=/^(?:0|[1-9]\d*)$/;function u(h,d){var f=typeof h;return d=d??l,!!d&&(f=="number"||f!="symbol"&&c.test(h))&&h>-1&&h%1==0&&h{var u=c("../../../../node_modules/lodash/eq.js"),h=c("../../../../node_modules/lodash/isArrayLike.js"),d=c("../../../../node_modules/lodash/_isIndex.js"),f=c("../../../../node_modules/lodash/isObject.js");function p(m,g,_){if(!f(_))return!1;var y=typeof g;return(y=="number"?h(_)&&d(g,_.length):y=="string"&&g in _)?u(_[g],m):!1}o.exports=p},"../../../../node_modules/lodash/_isKey.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isArray.js"),h=c("../../../../node_modules/lodash/isSymbol.js"),d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,f=/^\w*$/;function p(m,g){if(u(m))return!1;var _=typeof m;return _=="number"||_=="symbol"||_=="boolean"||m==null||h(m)?!0:f.test(m)||!d.test(m)||g!=null&&m in Object(g)}o.exports=p},"../../../../node_modules/lodash/_isKeyable.js":o=>{function l(c){var u=typeof c;return u=="string"||u=="number"||u=="symbol"||u=="boolean"?c!=="__proto__":c===null}o.exports=l},"../../../../node_modules/lodash/_isMasked.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_coreJsData.js"),h=function(){var f=/[^.]+$/.exec(u&&u.keys&&u.keys.IE_PROTO||"");return f?"Symbol(src)_1."+f:""}();function d(f){return!!h&&h in f}o.exports=d},"../../../../node_modules/lodash/_isPrototype.js":o=>{var l=Object.prototype;function c(u){var h=u&&u.constructor,d=typeof h=="function"&&h.prototype||l;return u===d}o.exports=c},"../../../../node_modules/lodash/_isStrictComparable.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isObject.js");function h(d){return d===d&&!u(d)}o.exports=h},"../../../../node_modules/lodash/_listCacheClear.js":o=>{function l(){this.__data__=[],this.size=0}o.exports=l},"../../../../node_modules/lodash/_listCacheDelete.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assocIndexOf.js"),h=Array.prototype,d=h.splice;function f(p){var m=this.__data__,g=u(m,p);if(g<0)return!1;var _=m.length-1;return g==_?m.pop():d.call(m,g,1),--this.size,!0}o.exports=f},"../../../../node_modules/lodash/_listCacheGet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assocIndexOf.js");function h(d){var f=this.__data__,p=u(f,d);return p<0?void 0:f[p][1]}o.exports=h},"../../../../node_modules/lodash/_listCacheHas.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assocIndexOf.js");function h(d){return u(this.__data__,d)>-1}o.exports=h},"../../../../node_modules/lodash/_listCacheSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assocIndexOf.js");function h(d,f){var p=this.__data__,m=u(p,d);return m<0?(++this.size,p.push([d,f])):p[m][1]=f,this}o.exports=h},"../../../../node_modules/lodash/_mapCacheClear.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_Hash.js"),h=c("../../../../node_modules/lodash/_ListCache.js"),d=c("../../../../node_modules/lodash/_Map.js");function f(){this.size=0,this.__data__={hash:new u,map:new(d||h),string:new u}}o.exports=f},"../../../../node_modules/lodash/_mapCacheDelete.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getMapData.js");function h(d){var f=u(this,d).delete(d);return this.size-=f?1:0,f}o.exports=h},"../../../../node_modules/lodash/_mapCacheGet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getMapData.js");function h(d){return u(this,d).get(d)}o.exports=h},"../../../../node_modules/lodash/_mapCacheHas.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getMapData.js");function h(d){return u(this,d).has(d)}o.exports=h},"../../../../node_modules/lodash/_mapCacheSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getMapData.js");function h(d,f){var p=u(this,d),m=p.size;return p.set(d,f),this.size+=p.size==m?0:1,this}o.exports=h},"../../../../node_modules/lodash/_mapToArray.js":o=>{function l(c){var u=-1,h=Array(c.size);return c.forEach(function(d,f){h[++u]=[f,d]}),h}o.exports=l},"../../../../node_modules/lodash/_matchesStrictComparable.js":o=>{function l(c,u){return function(h){return h==null?!1:h[c]===u&&(u!==void 0||c in Object(h))}}o.exports=l},"../../../../node_modules/lodash/_memoizeCapped.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/memoize.js"),h=500;function d(f){var p=u(f,function(g){return m.size===h&&m.clear(),g}),m=p.cache;return p}o.exports=d},"../../../../node_modules/lodash/_nativeCreate.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_getNative.js"),h=u(Object,"create");o.exports=h},"../../../../node_modules/lodash/_nativeKeys.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_overArg.js"),h=u(Object.keys,Object);o.exports=h},"../../../../node_modules/lodash/_nativeKeysIn.js":o=>{function l(c){var u=[];if(c!=null)for(var h in Object(c))u.push(h);return u}o.exports=l},"../../../../node_modules/lodash/_nodeUtil.js":(o,l,c)=>{o=c.nmd(o);var u=c("../../../../node_modules/lodash/_freeGlobal.js"),h=l&&!l.nodeType&&l,d=h&&!0&&o&&!o.nodeType&&o,f=d&&d.exports===h,p=f&&u.process,m=function(){try{var g=d&&d.require&&d.require("util").types;return g||p&&p.binding&&p.binding("util")}catch{}}();o.exports=m},"../../../../node_modules/lodash/_objectToString.js":o=>{var l=Object.prototype,c=l.toString;function u(h){return c.call(h)}o.exports=u},"../../../../node_modules/lodash/_overArg.js":o=>{function l(c,u){return function(h){return c(u(h))}}o.exports=l},"../../../../node_modules/lodash/_overRest.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_apply.js"),h=Math.max;function d(f,p,m){return p=h(p===void 0?f.length-1:p,0),function(){for(var g=arguments,_=-1,y=h(g.length-p,0),v=Array(y);++_{var u=c("../../../../node_modules/lodash/_freeGlobal.js"),h=typeof self=="object"&&self&&self.Object===Object&&self,d=u||h||Function("return this")();o.exports=d},"../../../../node_modules/lodash/_safeGet.js":o=>{function l(c,u){if(!(u==="constructor"&&typeof c[u]=="function")&&u!="__proto__")return c[u]}o.exports=l},"../../../../node_modules/lodash/_setCacheAdd.js":o=>{var l="__lodash_hash_undefined__";function c(u){return this.__data__.set(u,l),this}o.exports=c},"../../../../node_modules/lodash/_setCacheHas.js":o=>{function l(c){return this.__data__.has(c)}o.exports=l},"../../../../node_modules/lodash/_setToArray.js":o=>{function l(c){var u=-1,h=Array(c.size);return c.forEach(function(d){h[++u]=d}),h}o.exports=l},"../../../../node_modules/lodash/_setToString.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseSetToString.js"),h=c("../../../../node_modules/lodash/_shortOut.js"),d=h(u);o.exports=d},"../../../../node_modules/lodash/_shortOut.js":o=>{var l=800,c=16,u=Date.now;function h(d){var f=0,p=0;return function(){var m=u(),g=c-(m-p);if(p=m,g>0){if(++f>=l)return arguments[0]}else f=0;return d.apply(void 0,arguments)}}o.exports=h},"../../../../node_modules/lodash/_stackClear.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_ListCache.js");function h(){this.__data__=new u,this.size=0}o.exports=h},"../../../../node_modules/lodash/_stackDelete.js":o=>{function l(c){var u=this.__data__,h=u.delete(c);return this.size=u.size,h}o.exports=l},"../../../../node_modules/lodash/_stackGet.js":o=>{function l(c){return this.__data__.get(c)}o.exports=l},"../../../../node_modules/lodash/_stackHas.js":o=>{function l(c){return this.__data__.has(c)}o.exports=l},"../../../../node_modules/lodash/_stackSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_ListCache.js"),h=c("../../../../node_modules/lodash/_Map.js"),d=c("../../../../node_modules/lodash/_MapCache.js"),f=200;function p(m,g){var _=this.__data__;if(_ instanceof u){var y=_.__data__;if(!h||y.length{function l(c,u,h){for(var d=h-1,f=c.length;++d{var u=c("../../../../node_modules/lodash/_asciiSize.js"),h=c("../../../../node_modules/lodash/_hasUnicode.js"),d=c("../../../../node_modules/lodash/_unicodeSize.js");function f(p){return h(p)?d(p):u(p)}o.exports=f},"../../../../node_modules/lodash/_stringToPath.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_memoizeCapped.js"),h=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,d=/\\(\\)?/g,f=u(function(p){var m=[];return p.charCodeAt(0)===46&&m.push(""),p.replace(h,function(g,_,y,v){m.push(y?v.replace(d,"$1"):_||g)}),m});o.exports=f},"../../../../node_modules/lodash/_toKey.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isSymbol.js"),h=1/0;function d(f){if(typeof f=="string"||u(f))return f;var p=f+"";return p=="0"&&1/f==-h?"-0":p}o.exports=d},"../../../../node_modules/lodash/_toSource.js":o=>{var l=Function.prototype,c=l.toString;function u(h){if(h!=null){try{return c.call(h)}catch{}try{return h+""}catch{}}return""}o.exports=u},"../../../../node_modules/lodash/_trimmedEndIndex.js":o=>{var l=/\s/;function c(u){for(var h=u.length;h--&&l.test(u.charAt(h)););return h}o.exports=c},"../../../../node_modules/lodash/_unicodeSize.js":o=>{var l="\\ud800-\\udfff",c="\\u0300-\\u036f",u="\\ufe20-\\ufe2f",h="\\u20d0-\\u20ff",d=c+u+h,f="\\ufe0e\\ufe0f",p="["+l+"]",m="["+d+"]",g="\\ud83c[\\udffb-\\udfff]",_="(?:"+m+"|"+g+")",y="[^"+l+"]",v="(?:\\ud83c[\\udde6-\\uddff]){2}",x="[\\ud800-\\udbff][\\udc00-\\udfff]",A="\\u200d",b=_+"?",C="["+f+"]?",T="(?:"+A+"(?:"+[y,v,x].join("|")+")"+C+b+")*",w=C+b+T,P="(?:"+[y+m+"?",m,v,x,p].join("|")+")",M=RegExp(g+"(?="+g+")|"+P+w,"g");function R(I){for(var L=M.lastIndex=0;M.test(I);)++L;return L}o.exports=R},"../../../../node_modules/lodash/clone.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseClone.js"),h=4;function d(f){return u(f,h)}o.exports=d},"../../../../node_modules/lodash/cloneDeep.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseClone.js"),h=1,d=4;function f(p){return u(p,h|d)}o.exports=f},"../../../../node_modules/lodash/constant.js":o=>{function l(c){return function(){return c}}o.exports=l},"../../../../node_modules/lodash/defaults.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseRest.js"),h=c("../../../../node_modules/lodash/eq.js"),d=c("../../../../node_modules/lodash/_isIterateeCall.js"),f=c("../../../../node_modules/lodash/keysIn.js"),p=Object.prototype,m=p.hasOwnProperty,g=u(function(_,y){_=Object(_);var v=-1,x=y.length,A=x>2?y[2]:void 0;for(A&&d(y[0],y[1],A)&&(x=1);++v{o.exports=c("../../../../node_modules/lodash/forEach.js")},"../../../../node_modules/lodash/eq.js":o=>{function l(c,u){return c===u||c!==c&&u!==u}o.exports=l},"../../../../node_modules/lodash/filter.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayFilter.js"),h=c("../../../../node_modules/lodash/_baseFilter.js"),d=c("../../../../node_modules/lodash/_baseIteratee.js"),f=c("../../../../node_modules/lodash/isArray.js");function p(m,g){var _=f(m)?u:h;return _(m,d(g,3))}o.exports=p},"../../../../node_modules/lodash/find.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_createFind.js"),h=c("../../../../node_modules/lodash/findIndex.js"),d=u(h);o.exports=d},"../../../../node_modules/lodash/findIndex.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFindIndex.js"),h=c("../../../../node_modules/lodash/_baseIteratee.js"),d=c("../../../../node_modules/lodash/toInteger.js"),f=Math.max;function p(m,g,_){var y=m==null?0:m.length;if(!y)return-1;var v=_==null?0:d(_);return v<0&&(v=f(y+v,0)),u(m,h(g,3),v)}o.exports=p},"../../../../node_modules/lodash/flatten.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFlatten.js");function h(d){var f=d==null?0:d.length;return f?u(d,1):[]}o.exports=h},"../../../../node_modules/lodash/forEach.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayEach.js"),h=c("../../../../node_modules/lodash/_baseEach.js"),d=c("../../../../node_modules/lodash/_castFunction.js"),f=c("../../../../node_modules/lodash/isArray.js");function p(m,g){var _=f(m)?u:h;return _(m,d(g))}o.exports=p},"../../../../node_modules/lodash/forIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFor.js"),h=c("../../../../node_modules/lodash/_castFunction.js"),d=c("../../../../node_modules/lodash/keysIn.js");function f(p,m){return p==null?p:u(p,h(m),d)}o.exports=f},"../../../../node_modules/lodash/get.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGet.js");function h(d,f,p){var m=d==null?void 0:u(d,f);return m===void 0?p:m}o.exports=h},"../../../../node_modules/lodash/has.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseHas.js"),h=c("../../../../node_modules/lodash/_hasPath.js");function d(f,p){return f!=null&&h(f,p,u)}o.exports=d},"../../../../node_modules/lodash/hasIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseHasIn.js"),h=c("../../../../node_modules/lodash/_hasPath.js");function d(f,p){return f!=null&&h(f,p,u)}o.exports=d},"../../../../node_modules/lodash/identity.js":o=>{function l(c){return c}o.exports=l},"../../../../node_modules/lodash/isArguments.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsArguments.js"),h=c("../../../../node_modules/lodash/isObjectLike.js"),d=Object.prototype,f=d.hasOwnProperty,p=d.propertyIsEnumerable,m=u(function(){return arguments}())?u:function(g){return h(g)&&f.call(g,"callee")&&!p.call(g,"callee")};o.exports=m},"../../../../node_modules/lodash/isArray.js":o=>{var l=Array.isArray;o.exports=l},"../../../../node_modules/lodash/isArrayLike.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isFunction.js"),h=c("../../../../node_modules/lodash/isLength.js");function d(f){return f!=null&&h(f.length)&&!u(f)}o.exports=d},"../../../../node_modules/lodash/isArrayLikeObject.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/isArrayLike.js"),h=c("../../../../node_modules/lodash/isObjectLike.js");function d(f){return h(f)&&u(f)}o.exports=d},"../../../../node_modules/lodash/isBuffer.js":(o,l,c)=>{o=c.nmd(o);var u=c("../../../../node_modules/lodash/_root.js"),h=c("../../../../node_modules/lodash/stubFalse.js"),d=l&&!l.nodeType&&l,f=d&&!0&&o&&!o.nodeType&&o,p=f&&f.exports===d,m=p?u.Buffer:void 0,g=m?m.isBuffer:void 0,_=g||h;o.exports=_},"../../../../node_modules/lodash/isEmpty.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseKeys.js"),h=c("../../../../node_modules/lodash/_getTag.js"),d=c("../../../../node_modules/lodash/isArguments.js"),f=c("../../../../node_modules/lodash/isArray.js"),p=c("../../../../node_modules/lodash/isArrayLike.js"),m=c("../../../../node_modules/lodash/isBuffer.js"),g=c("../../../../node_modules/lodash/_isPrototype.js"),_=c("../../../../node_modules/lodash/isTypedArray.js"),y="[object Map]",v="[object Set]",x=Object.prototype,A=x.hasOwnProperty;function b(C){if(C==null)return!0;if(p(C)&&(f(C)||typeof C=="string"||typeof C.splice=="function"||m(C)||_(C)||d(C)))return!C.length;var T=h(C);if(T==y||T==v)return!C.size;if(g(C))return!u(C).length;for(var w in C)if(A.call(C,w))return!1;return!0}o.exports=b},"../../../../node_modules/lodash/isFunction.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetTag.js"),h=c("../../../../node_modules/lodash/isObject.js"),d="[object AsyncFunction]",f="[object Function]",p="[object GeneratorFunction]",m="[object Proxy]";function g(_){if(!h(_))return!1;var y=u(_);return y==f||y==p||y==d||y==m}o.exports=g},"../../../../node_modules/lodash/isLength.js":o=>{var l=9007199254740991;function c(u){return typeof u=="number"&&u>-1&&u%1==0&&u<=l}o.exports=c},"../../../../node_modules/lodash/isMap.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsMap.js"),h=c("../../../../node_modules/lodash/_baseUnary.js"),d=c("../../../../node_modules/lodash/_nodeUtil.js"),f=d&&d.isMap,p=f?h(f):u;o.exports=p},"../../../../node_modules/lodash/isObject.js":o=>{function l(c){var u=typeof c;return c!=null&&(u=="object"||u=="function")}o.exports=l},"../../../../node_modules/lodash/isObjectLike.js":o=>{function l(c){return c!=null&&typeof c=="object"}o.exports=l},"../../../../node_modules/lodash/isPlainObject.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetTag.js"),h=c("../../../../node_modules/lodash/_getPrototype.js"),d=c("../../../../node_modules/lodash/isObjectLike.js"),f="[object Object]",p=Function.prototype,m=Object.prototype,g=p.toString,_=m.hasOwnProperty,y=g.call(Object);function v(x){if(!d(x)||u(x)!=f)return!1;var A=h(x);if(A===null)return!0;var b=_.call(A,"constructor")&&A.constructor;return typeof b=="function"&&b instanceof b&&g.call(b)==y}o.exports=v},"../../../../node_modules/lodash/isSet.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsSet.js"),h=c("../../../../node_modules/lodash/_baseUnary.js"),d=c("../../../../node_modules/lodash/_nodeUtil.js"),f=d&&d.isSet,p=f?h(f):u;o.exports=p},"../../../../node_modules/lodash/isString.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetTag.js"),h=c("../../../../node_modules/lodash/isArray.js"),d=c("../../../../node_modules/lodash/isObjectLike.js"),f="[object String]";function p(m){return typeof m=="string"||!h(m)&&d(m)&&u(m)==f}o.exports=p},"../../../../node_modules/lodash/isSymbol.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseGetTag.js"),h=c("../../../../node_modules/lodash/isObjectLike.js"),d="[object Symbol]";function f(p){return typeof p=="symbol"||h(p)&&u(p)==d}o.exports=f},"../../../../node_modules/lodash/isTypedArray.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseIsTypedArray.js"),h=c("../../../../node_modules/lodash/_baseUnary.js"),d=c("../../../../node_modules/lodash/_nodeUtil.js"),f=d&&d.isTypedArray,p=f?h(f):u;o.exports=p},"../../../../node_modules/lodash/isUndefined.js":o=>{function l(c){return c===void 0}o.exports=l},"../../../../node_modules/lodash/keys.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayLikeKeys.js"),h=c("../../../../node_modules/lodash/_baseKeys.js"),d=c("../../../../node_modules/lodash/isArrayLike.js");function f(p){return d(p)?u(p):h(p)}o.exports=f},"../../../../node_modules/lodash/keysIn.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayLikeKeys.js"),h=c("../../../../node_modules/lodash/_baseKeysIn.js"),d=c("../../../../node_modules/lodash/isArrayLike.js");function f(p){return d(p)?u(p,!0):h(p)}o.exports=f},"../../../../node_modules/lodash/last.js":o=>{function l(c){var u=c==null?0:c.length;return u?c[u-1]:void 0}o.exports=l},"../../../../node_modules/lodash/map.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayMap.js"),h=c("../../../../node_modules/lodash/_baseIteratee.js"),d=c("../../../../node_modules/lodash/_baseMap.js"),f=c("../../../../node_modules/lodash/isArray.js");function p(m,g){var _=f(m)?u:d;return _(m,h(g,3))}o.exports=p},"../../../../node_modules/lodash/mapValues.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseAssignValue.js"),h=c("../../../../node_modules/lodash/_baseForOwn.js"),d=c("../../../../node_modules/lodash/_baseIteratee.js");function f(p,m){var g={};return m=d(m,3),h(p,function(_,y,v){u(g,y,m(_,y,v))}),g}o.exports=f},"../../../../node_modules/lodash/max.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseExtremum.js"),h=c("../../../../node_modules/lodash/_baseGt.js"),d=c("../../../../node_modules/lodash/identity.js");function f(p){return p&&p.length?u(p,d,h):void 0}o.exports=f},"../../../../node_modules/lodash/memoize.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_MapCache.js"),h="Expected a function";function d(f,p){if(typeof f!="function"||p!=null&&typeof p!="function")throw new TypeError(h);var m=function(){var g=arguments,_=p?p.apply(this,g):g[0],y=m.cache;if(y.has(_))return y.get(_);var v=f.apply(this,g);return m.cache=y.set(_,v)||y,v};return m.cache=new(d.Cache||u),m}d.Cache=u,o.exports=d},"../../../../node_modules/lodash/merge.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseMerge.js"),h=c("../../../../node_modules/lodash/_createAssigner.js"),d=h(function(f,p,m){u(f,p,m)});o.exports=d},"../../../../node_modules/lodash/min.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseExtremum.js"),h=c("../../../../node_modules/lodash/_baseLt.js"),d=c("../../../../node_modules/lodash/identity.js");function f(p){return p&&p.length?u(p,d,h):void 0}o.exports=f},"../../../../node_modules/lodash/minBy.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseExtremum.js"),h=c("../../../../node_modules/lodash/_baseIteratee.js"),d=c("../../../../node_modules/lodash/_baseLt.js");function f(p,m){return p&&p.length?u(p,h(m,2),d):void 0}o.exports=f},"../../../../node_modules/lodash/noop.js":o=>{function l(){}o.exports=l},"../../../../node_modules/lodash/now.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_root.js"),h=function(){return u.Date.now()};o.exports=h},"../../../../node_modules/lodash/pick.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_basePick.js"),h=c("../../../../node_modules/lodash/_flatRest.js"),d=h(function(f,p){return f==null?{}:u(f,p)});o.exports=d},"../../../../node_modules/lodash/property.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseProperty.js"),h=c("../../../../node_modules/lodash/_basePropertyDeep.js"),d=c("../../../../node_modules/lodash/_isKey.js"),f=c("../../../../node_modules/lodash/_toKey.js");function p(m){return d(m)?u(f(m)):h(m)}o.exports=p},"../../../../node_modules/lodash/range.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_createRange.js"),h=u();o.exports=h},"../../../../node_modules/lodash/reduce.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayReduce.js"),h=c("../../../../node_modules/lodash/_baseEach.js"),d=c("../../../../node_modules/lodash/_baseIteratee.js"),f=c("../../../../node_modules/lodash/_baseReduce.js"),p=c("../../../../node_modules/lodash/isArray.js");function m(g,_,y){var v=p(g)?u:f,x=arguments.length<3;return v(g,d(_,4),y,x,h)}o.exports=m},"../../../../node_modules/lodash/size.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseKeys.js"),h=c("../../../../node_modules/lodash/_getTag.js"),d=c("../../../../node_modules/lodash/isArrayLike.js"),f=c("../../../../node_modules/lodash/isString.js"),p=c("../../../../node_modules/lodash/_stringSize.js"),m="[object Map]",g="[object Set]";function _(y){if(y==null)return 0;if(d(y))return f(y)?p(y):y.length;var v=h(y);return v==m||v==g?y.size:u(y).length}o.exports=_},"../../../../node_modules/lodash/sortBy.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFlatten.js"),h=c("../../../../node_modules/lodash/_baseOrderBy.js"),d=c("../../../../node_modules/lodash/_baseRest.js"),f=c("../../../../node_modules/lodash/_isIterateeCall.js"),p=d(function(m,g){if(m==null)return[];var _=g.length;return _>1&&f(m,g[0],g[1])?g=[]:_>2&&f(g[0],g[1],g[2])&&(g=[g[0]]),h(m,u(g,1),[])});o.exports=p},"../../../../node_modules/lodash/stubArray.js":o=>{function l(){return[]}o.exports=l},"../../../../node_modules/lodash/stubFalse.js":o=>{function l(){return!1}o.exports=l},"../../../../node_modules/lodash/toFinite.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/toNumber.js"),h=1/0,d=17976931348623157e292;function f(p){if(!p)return p===0?p:0;if(p=u(p),p===h||p===-h){var m=p<0?-1:1;return m*d}return p===p?p:0}o.exports=f},"../../../../node_modules/lodash/toInteger.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/toFinite.js");function h(d){var f=u(d),p=f%1;return f===f?p?f-p:f:0}o.exports=h},"../../../../node_modules/lodash/toNumber.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseTrim.js"),h=c("../../../../node_modules/lodash/isObject.js"),d=c("../../../../node_modules/lodash/isSymbol.js"),f=NaN,p=/^[-+]0x[0-9a-f]+$/i,m=/^0b[01]+$/i,g=/^0o[0-7]+$/i,_=parseInt;function y(v){if(typeof v=="number")return v;if(d(v))return f;if(h(v)){var x=typeof v.valueOf=="function"?v.valueOf():v;v=h(x)?x+"":x}if(typeof v!="string")return v===0?v:+v;v=u(v);var A=m.test(v);return A||g.test(v)?_(v.slice(2),A?2:8):p.test(v)?f:+v}o.exports=y},"../../../../node_modules/lodash/toPlainObject.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_copyObject.js"),h=c("../../../../node_modules/lodash/keysIn.js");function d(f){return u(f,h(f))}o.exports=d},"../../../../node_modules/lodash/toString.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseToString.js");function h(d){return d==null?"":u(d)}o.exports=h},"../../../../node_modules/lodash/transform.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_arrayEach.js"),h=c("../../../../node_modules/lodash/_baseCreate.js"),d=c("../../../../node_modules/lodash/_baseForOwn.js"),f=c("../../../../node_modules/lodash/_baseIteratee.js"),p=c("../../../../node_modules/lodash/_getPrototype.js"),m=c("../../../../node_modules/lodash/isArray.js"),g=c("../../../../node_modules/lodash/isBuffer.js"),_=c("../../../../node_modules/lodash/isFunction.js"),y=c("../../../../node_modules/lodash/isObject.js"),v=c("../../../../node_modules/lodash/isTypedArray.js");function x(A,b,C){var T=m(A),w=T||g(A)||v(A);if(b=f(b,4),C==null){var P=A&&A.constructor;w?C=T?new P:[]:y(A)?C=_(P)?h(p(A)):{}:C={}}return(w?u:d)(A,function(M,R,I){return b(C,M,R,I)}),C}o.exports=x},"../../../../node_modules/lodash/union.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseFlatten.js"),h=c("../../../../node_modules/lodash/_baseRest.js"),d=c("../../../../node_modules/lodash/_baseUniq.js"),f=c("../../../../node_modules/lodash/isArrayLikeObject.js"),p=h(function(m){return d(u(m,1,f,!0))});o.exports=p},"../../../../node_modules/lodash/uniqueId.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/toString.js"),h=0;function d(f){var p=++h;return u(f)+p}o.exports=d},"../../../../node_modules/lodash/values.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_baseValues.js"),h=c("../../../../node_modules/lodash/keys.js");function d(f){return f==null?[]:u(f,h(f))}o.exports=d},"../../../../node_modules/lodash/zipObject.js":(o,l,c)=>{var u=c("../../../../node_modules/lodash/_assignValue.js"),h=c("../../../../node_modules/lodash/_baseZipObject.js");function d(f,p){return h(f||[],p||[],u)}o.exports=d},"../../../../node_modules/object-assign/index.js":o=>{/* object-assign (c) Sindre Sorhus @license MIT */var l=Object.getOwnPropertySymbols,c=Object.prototype.hasOwnProperty,u=Object.prototype.propertyIsEnumerable;function h(f){if(f==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(f)}function d(){try{if(!Object.assign)return!1;var f=new String("abc");if(f[5]="de",Object.getOwnPropertyNames(f)[0]==="5")return!1;for(var p={},m=0;m<10;m++)p["_"+String.fromCharCode(m)]=m;var g=Object.getOwnPropertyNames(p).map(function(y){return p[y]});if(g.join("")!=="0123456789")return!1;var _={};return"abcdefghijklmnopqrst".split("").forEach(function(y){_[y]=y}),Object.keys(Object.assign({},_)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}o.exports=d()?Object.assign:function(f,p){for(var m,g=h(f),_,y=1;y{var u=function(){};{var h=c("../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js"),d={},f=c("../../../../node_modules/prop-types/lib/has.js");u=function(m){var g="Warning: "+m;typeof console<"u"&&console.error(g);try{throw new Error(g)}catch{}}}function p(m,g,_,y,v){for(var x in m)if(f(m,x)){var A;try{if(typeof m[x]!="function"){var b=Error((y||"React class")+": "+_+" type `"+x+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof m[x]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw b.name="Invariant Violation",b}A=m[x](g,x,y,_,null,h)}catch(T){A=T}if(A&&!(A instanceof Error)&&u((y||"React class")+": type specification of "+_+" `"+x+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof A+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),A instanceof Error&&!(A.message in d)){d[A.message]=!0;var C=v?v():"";u("Failed "+_+" type: "+A.message+(C??""))}}}p.resetWarningCache=function(){d={}},o.exports=p},"../../../../node_modules/prop-types/factoryWithTypeCheckers.js":(o,l,c)=>{var u=c("../../../../node_modules/prop-types/node_modules/react-is/index.js"),h=c("../../../../node_modules/object-assign/index.js"),d=c("../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js"),f=c("../../../../node_modules/prop-types/lib/has.js"),p=c("../../../../node_modules/prop-types/checkPropTypes.js"),m=function(){};m=function(_){var y="Warning: "+_;typeof console<"u"&&console.error(y);try{throw new Error(y)}catch{}};function g(){return null}o.exports=function(_,y){var v=typeof Symbol=="function"&&Symbol.iterator,x="@@iterator";function A(B){var Y=B&&(v&&B[v]||B[x]);if(typeof Y=="function")return Y}var b="<>",C={array:M("array"),bigint:M("bigint"),bool:M("boolean"),func:M("function"),number:M("number"),object:M("object"),string:M("string"),symbol:M("symbol"),any:R(),arrayOf:I,element:L(),elementType:k(),instanceOf:V,node:K(),objectOf:j,oneOf:H,oneOfType:z,shape:W,exact:Z};function T(B,Y){return B===Y?B!==0||1/B===1/Y:B!==B&&Y!==Y}function w(B,Y){this.message=B,this.data=Y&&typeof Y=="object"?Y:{},this.stack=""}w.prototype=Error.prototype;function P(B){var Y={},te=0;function oe(pe,ye,Ie,Ne,Ve,nt,Ke){if(Ne=Ne||b,nt=nt||Ie,Ke!==d){if(y){var Et=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw Et.name="Invariant Violation",Et}else if(typeof console<"u"){var ft=Ne+":"+Ie;!Y[ft]&&te<3&&(m("You are manually calling a React.PropTypes validation function for the `"+nt+"` prop on `"+Ne+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),Y[ft]=!0,te++)}}return ye[Ie]==null?pe?ye[Ie]===null?new w("The "+Ve+" `"+nt+"` is marked as required "+("in `"+Ne+"`, but its value is `null`.")):new w("The "+Ve+" `"+nt+"` is marked as required in "+("`"+Ne+"`, but its value is `undefined`.")):null:B(ye,Ie,Ne,Ve,nt)}var ne=oe.bind(null,!1);return ne.isRequired=oe.bind(null,!0),ne}function M(B){function Y(te,oe,ne,pe,ye,Ie){var Ne=te[oe],Ve=ae(Ne);if(Ve!==B){var nt=ue(Ne);return new w("Invalid "+pe+" `"+ye+"` of type "+("`"+nt+"` supplied to `"+ne+"`, expected ")+("`"+B+"`."),{expectedType:B})}return null}return P(Y)}function R(){return P(g)}function I(B){function Y(te,oe,ne,pe,ye){if(typeof B!="function")return new w("Property `"+ye+"` of component `"+ne+"` has invalid PropType notation inside arrayOf.");var Ie=te[oe];if(!Array.isArray(Ie)){var Ne=ae(Ie);return new w("Invalid "+pe+" `"+ye+"` of type "+("`"+Ne+"` supplied to `"+ne+"`, expected an array."))}for(var Ve=0;Ve1?m("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."):m("Invalid argument supplied to oneOf, expected an array."),g;function Y(te,oe,ne,pe,ye){for(var Ie=te[oe],Ne=0;Ne0?", expected one of type ["+Ve.join(", ")+"]":"";return new w("Invalid "+Ie+" `"+Ne+"` supplied to "+("`"+ye+"`"+ft+"."))}return P(oe)}function K(){function B(Y,te,oe,ne,pe){return q(Y[te])?null:new w("Invalid "+ne+" `"+pe+"` supplied to "+("`"+oe+"`, expected a ReactNode."))}return P(B)}function U(B,Y,te,oe,ne){return new w((B||"React class")+": "+Y+" type `"+te+"."+oe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+ne+"`.")}function W(B){function Y(te,oe,ne,pe,ye){var Ie=te[oe],Ne=ae(Ie);if(Ne!=="object")return new w("Invalid "+pe+" `"+ye+"` of type `"+Ne+"` "+("supplied to `"+ne+"`, expected `object`."));for(var Ve in B){var nt=B[Ve];if(typeof nt!="function")return U(ne,pe,ye,Ve,ue(nt));var Ke=nt(Ie,Ve,ne,pe,ye+"."+Ve,d);if(Ke)return Ke}return null}return P(Y)}function Z(B){function Y(te,oe,ne,pe,ye){var Ie=te[oe],Ne=ae(Ie);if(Ne!=="object")return new w("Invalid "+pe+" `"+ye+"` of type `"+Ne+"` "+("supplied to `"+ne+"`, expected `object`."));var Ve=h({},te[oe],B);for(var nt in Ve){var Ke=B[nt];if(f(B,nt)&&typeof Ke!="function")return U(ne,pe,ye,nt,ue(Ke));if(!Ke)return new w("Invalid "+pe+" `"+ye+"` key `"+nt+"` supplied to `"+ne+"`.\nBad object: "+JSON.stringify(te[oe],null," ")+` Valid keys: `+JSON.stringify(Object.keys(B),null," "));var Et=Ke(Ie,nt,ne,pe,ye+"."+nt,d);if(Et)return Et}return null}return P(Y)}function q(B){switch(typeof B){case"number":case"string":case"undefined":return!0;case"boolean":return!B;case"object":if(Array.isArray(B))return B.every(q);if(B===null||_(B))return!0;var Y=A(B);if(Y){var te=Y.call(B),oe;if(Y!==B.entries){for(;!(oe=te.next()).done;)if(!q(oe.value))return!1}else for(;!(oe=te.next()).done;){var ne=oe.value;if(ne&&!q(ne[1]))return!1}}else return!1;return!0;default:return!1}}function ie(B,Y){return B==="symbol"?!0:Y?Y["@@toStringTag"]==="Symbol"||typeof Symbol=="function"&&Y instanceof Symbol:!1}function ae(B){var Y=typeof B;return Array.isArray(B)?"array":B instanceof RegExp?"object":ie(Y,B)?"symbol":Y}function ue(B){if(typeof B>"u"||B===null)return""+B;var Y=ae(B);if(Y==="object"){if(B instanceof Date)return"date";if(B instanceof RegExp)return"regexp"}return Y}function ce(B){var Y=ue(B);switch(Y){case"array":case"object":return"an "+Y;case"boolean":case"date":case"regexp":return"a "+Y;default:return Y}}function N(B){return!B.constructor||!B.constructor.name?b:B.constructor.name}return C.checkPropTypes=p,C.resetWarningCache=p.resetWarningCache,C.PropTypes=C,C}},"../../../../node_modules/prop-types/index.js":(o,l,c)=>{{var u=c("../../../../node_modules/prop-types/node_modules/react-is/index.js"),h=!0;o.exports=c("../../../../node_modules/prop-types/factoryWithTypeCheckers.js")(u.isElement,h)}},"../../../../node_modules/prop-types/lib/ReactPropTypesSecret.js":o=>{var l="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";o.exports=l},"../../../../node_modules/prop-types/lib/has.js":o=>{o.exports=Function.call.bind(Object.prototype.hasOwnProperty)},"../../../../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js":(o,l)=>{/** @license React v16.13.1 * react-is.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(){var c=typeof Symbol=="function"&&Symbol.for,u=c?Symbol.for("react.element"):60103,h=c?Symbol.for("react.portal"):60106,d=c?Symbol.for("react.fragment"):60107,f=c?Symbol.for("react.strict_mode"):60108,p=c?Symbol.for("react.profiler"):60114,m=c?Symbol.for("react.provider"):60109,g=c?Symbol.for("react.context"):60110,_=c?Symbol.for("react.async_mode"):60111,y=c?Symbol.for("react.concurrent_mode"):60111,v=c?Symbol.for("react.forward_ref"):60112,x=c?Symbol.for("react.suspense"):60113,A=c?Symbol.for("react.suspense_list"):60120,b=c?Symbol.for("react.memo"):60115,C=c?Symbol.for("react.lazy"):60116,T=c?Symbol.for("react.block"):60121,w=c?Symbol.for("react.fundamental"):60117,P=c?Symbol.for("react.responder"):60118,M=c?Symbol.for("react.scope"):60119;function R(Ke){return typeof Ke=="string"||typeof Ke=="function"||Ke===d||Ke===y||Ke===p||Ke===f||Ke===x||Ke===A||typeof Ke=="object"&&Ke!==null&&(Ke.$$typeof===C||Ke.$$typeof===b||Ke.$$typeof===m||Ke.$$typeof===g||Ke.$$typeof===v||Ke.$$typeof===w||Ke.$$typeof===P||Ke.$$typeof===M||Ke.$$typeof===T)}function I(Ke){if(typeof Ke=="object"&&Ke!==null){var Et=Ke.$$typeof;switch(Et){case u:var ft=Ke.type;switch(ft){case _:case y:case d:case p:case f:case x:return ft;default:var Tt=ft&&ft.$$typeof;switch(Tt){case g:case v:case C:case b:case m:return Tt;default:return Et}}case h:return Et}}}var L=_,k=y,V=g,H=m,j=u,z=v,K=d,U=C,W=b,Z=h,q=p,ie=f,ae=x,ue=!1;function ce(Ke){return ue||(ue=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),N(Ke)||I(Ke)===_}function N(Ke){return I(Ke)===y}function B(Ke){return I(Ke)===g}function Y(Ke){return I(Ke)===m}function te(Ke){return typeof Ke=="object"&&Ke!==null&&Ke.$$typeof===u}function oe(Ke){return I(Ke)===v}function ne(Ke){return I(Ke)===d}function pe(Ke){return I(Ke)===C}function ye(Ke){return I(Ke)===b}function Ie(Ke){return I(Ke)===h}function Ne(Ke){return I(Ke)===p}function Ve(Ke){return I(Ke)===f}function nt(Ke){return I(Ke)===x}l.AsyncMode=L,l.ConcurrentMode=k,l.ContextConsumer=V,l.ContextProvider=H,l.Element=j,l.ForwardRef=z,l.Fragment=K,l.Lazy=U,l.Memo=W,l.Portal=Z,l.Profiler=q,l.StrictMode=ie,l.Suspense=ae,l.isAsyncMode=ce,l.isConcurrentMode=N,l.isContextConsumer=B,l.isContextProvider=Y,l.isElement=te,l.isForwardRef=oe,l.isFragment=ne,l.isLazy=pe,l.isMemo=ye,l.isPortal=Ie,l.isProfiler=Ne,l.isStrictMode=Ve,l.isSuspense=nt,l.isValidElementType=R,l.typeOf=I})()},"../../../../node_modules/prop-types/node_modules/react-is/index.js":(o,l,c)=>{o.exports=c("../../../../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js")},"../../../../node_modules/react-dom/cjs/react-dom.development.js":(o,l,c)=>{/** @license React v17.0.2 * react-dom.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(){var u=c("../../../../node_modules/react/index.js"),h=c("../../../../node_modules/object-assign/index.js"),d=c("../../../../node_modules/scheduler/index.js"),f=c("../../../../node_modules/scheduler/tracing.js"),p=u.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function m(S){{for(var E=arguments.length,O=new Array(E>1?E-1:0),G=1;G1?E-1:0),G=1;G2&&(S[0]==="o"||S[0]==="O")&&(S[1]==="n"||S[1]==="N")}function Si(S,E,O,G){if(O!==null&&O.type===Ie)return!1;switch(typeof E){case"function":case"symbol":return!0;case"boolean":{if(G)return!1;if(O!==null)return!O.acceptsBooleans;var Q=S.toLowerCase().slice(0,5);return Q!=="data-"&&Q!=="aria-"}default:return!1}}function dr(S,E,O,G){if(E===null||typeof E>"u"||Si(S,E,O,G))return!0;if(G)return!1;if(O!==null)switch(O.type){case nt:return!E;case Ke:return E===!1;case Et:return isNaN(E);case ft:return isNaN(E)||E<1}return!1}function Hi(S){return rr.hasOwnProperty(S)?rr[S]:null}function er(S,E,O,G,Q,re,le){this.acceptsBooleans=E===Ve||E===nt||E===Ke,this.attributeName=G,this.attributeNamespace=Q,this.mustUseProperty=O,this.propertyName=S,this.type=E,this.sanitizeURL=re,this.removeEmptyString=le}var rr={},Dr=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];Dr.forEach(function(S){rr[S]=new er(S,Ie,!1,S,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(S){var E=S[0],O=S[1];rr[E]=new er(E,Ne,!1,O,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(S){rr[S]=new er(S,Ve,!1,S.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(S){rr[S]=new er(S,Ve,!1,S,null,!1,!1)}),["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","disablePictureInPicture","disableRemotePlayback","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(function(S){rr[S]=new er(S,nt,!1,S.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(S){rr[S]=new er(S,nt,!0,S,null,!1,!1)}),["capture","download"].forEach(function(S){rr[S]=new er(S,Ke,!1,S,null,!1,!1)}),["cols","rows","size","span"].forEach(function(S){rr[S]=new er(S,ft,!1,S,null,!1,!1)}),["rowSpan","start"].forEach(function(S){rr[S]=new er(S,Et,!1,S.toLowerCase(),null,!1,!1)});var Wt=/[\-\:]([a-z])/g,ni=function(S){return S[1].toUpperCase()};["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(function(S){var E=S.replace(Wt,ni);rr[E]=new er(E,Ne,!1,S,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(S){var E=S.replace(Wt,ni);rr[E]=new er(E,Ne,!1,S,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(S){var E=S.replace(Wt,ni);rr[E]=new er(E,Ne,!1,S,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(S){rr[S]=new er(S,Ne,!1,S.toLowerCase(),null,!1,!1)});var Yt="xlinkHref";rr[Yt]=new er("xlinkHref",Ne,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(S){rr[S]=new er(S,Ne,!1,S.toLowerCase(),null,!0,!0)});var Ni=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i,ar=!1;function Cr(S){!ar&&Ni.test(S)&&(ar=!0,g("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.",JSON.stringify(S)))}function xs(S,E,O,G){if(G.mustUseProperty){var Q=G.propertyName;return S[Q]}else{G.sanitizeURL&&Cr(""+O);var re=G.attributeName,le=null;if(G.type===Ke){if(S.hasAttribute(re)){var ge=S.getAttribute(re);return ge===""?!0:dr(E,O,G,!1)?ge:ge===""+O?O:ge}}else if(S.hasAttribute(re)){if(dr(E,O,G,!1))return S.getAttribute(re);if(G.type===nt)return O;le=S.getAttribute(re)}return dr(E,O,G,!1)?le===null?O:le:le===""+O?O:le}}function gn(S,E,O){{if(!Ti(E))return;if(qK(O))return O;if(!S.hasAttribute(E))return O===void 0?void 0:null;var G=S.getAttribute(E);return G===""+O?O:G}}function As(S,E,O,G){var Q=Hi(E);if(!Yi(E,Q,G)){if(dr(E,O,Q,G)&&(O=null),G||Q===null){if(Ti(E)){var re=E;O===null?S.removeAttribute(re):S.setAttribute(re,""+O)}return}var le=Q.mustUseProperty;if(le){var ge=Q.propertyName;if(O===null){var Se=Q.type;S[ge]=Se===nt?!1:""}else S[ge]=O;return}var Oe=Q.attributeName,Be=Q.attributeNamespace;if(O===null)S.removeAttribute(Oe);else{var lt=Q.type,He;lt===nt||lt===Ke&&O===!0?He="":(He=""+O,Q.sanitizeURL&&Cr(He.toString())),Be?S.setAttributeNS(Be,Oe,He):S.setAttribute(Oe,He)}}}var jt=60103,cs=60106,Bn=60107,Cn=60108,or=60114,wt=60109,mi=60110,Vt=60112,$s=60113,Is=60120,tn=60115,_l=60116,We=60121,Gt=60119,gi=60128,fr=60129,Vs=60130,Ps=60131;if(typeof Symbol=="function"&&Symbol.for){var sr=Symbol.for;jt=sr("react.element"),cs=sr("react.portal"),Bn=sr("react.fragment"),Cn=sr("react.strict_mode"),or=sr("react.profiler"),wt=sr("react.provider"),mi=sr("react.context"),Vt=sr("react.forward_ref"),$s=sr("react.suspense"),Is=sr("react.suspense_list"),tn=sr("react.memo"),_l=sr("react.lazy"),We=sr("react.block"),sr("react.server.block"),sr("react.fundamental"),Gt=sr("react.scope"),gi=sr("react.opaque.id"),fr=sr("react.debug_trace_mode"),Vs=sr("react.offscreen"),Ps=sr("react.legacy_hidden")}var jr=typeof Symbol=="function"&&Symbol.iterator,Oo="@@iterator";function Ur(S){if(S===null||typeof S!="object")return null;var E=jr&&S[jr]||S[Oo];return typeof E=="function"?E:null}var as=0,Bl,_c,Ku,tc,Ih,U0,dp;function Eg(){}Eg.__reactDisabledLog=!0;function vc(){{if(as===0){Bl=console.log,_c=console.info,Ku=console.warn,tc=console.error,Ih=console.group,U0=console.groupCollapsed,dp=console.groupEnd;var S={configurable:!0,enumerable:!0,value:Eg,writable:!0};Object.defineProperties(console,{info:S,log:S,warn:S,error:S,group:S,groupCollapsed:S,groupEnd:S})}as++}}function yc(){{if(as--,as===0){var S={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:h({},S,{value:Bl}),info:h({},S,{value:_c}),warn:h({},S,{value:Ku}),error:h({},S,{value:tc}),group:h({},S,{value:Ih}),groupCollapsed:h({},S,{value:U0}),groupEnd:h({},S,{value:dp})})}as<0&&g("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var rf=p.ReactCurrentDispatcher,Ph;function No(S,E,O){{if(Ph===void 0)try{throw Error()}catch(Q){var G=Q.stack.trim().match(/\n( *(at )?)/);Ph=G&&G[1]||""}return` `+Ph+S}}var sf=!1,z0;{var V0=typeof WeakMap=="function"?WeakMap:Map;z0=new V0}function fp(S,E){if(!S||sf)return"";{var O=z0.get(S);if(O!==void 0)return O}var G;sf=!0;var Q=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var re;re=rf.current,rf.current=null,vc();try{if(E){var le=function(){throw Error()};if(Object.defineProperty(le.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(le,[])}catch(Bt){G=Bt}Reflect.construct(S,[],le)}else{try{le.call()}catch(Bt){G=Bt}S.call(le.prototype)}}else{try{throw Error()}catch(Bt){G=Bt}S()}}catch(Bt){if(Bt&&G&&typeof Bt.stack=="string"){for(var ge=Bt.stack.split(` `),Se=G.stack.split(` `),Oe=ge.length-1,Be=Se.length-1;Oe>=1&&Be>=0&&ge[Oe]!==Se[Be];)Be--;for(;Oe>=1&&Be>=0;Oe--,Be--)if(ge[Oe]!==Se[Be]){if(Oe!==1||Be!==1)do if(Oe--,Be--,Be<0||ge[Oe]!==Se[Be]){var lt=` `+ge[Oe].replace(" at new "," at ");return typeof S=="function"&&z0.set(S,lt),lt}while(Oe>=1&&Be>=0);break}}}finally{sf=!1,rf.current=re,yc(),Error.prepareStackTrace=Q}var He=S?S.displayName||S.name:"",ht=He?No(He):"";return typeof S=="function"&&z0.set(S,ht),ht}function Tg(S,E,O){return fp(S,!0)}function Hu(S,E,O){return fp(S,!1)}function Mg(S){var E=S.prototype;return!!(E&&E.isReactComponent)}function pp(S,E,O){if(S==null)return"";if(typeof S=="function")return fp(S,Mg(S));if(typeof S=="string")return No(S);switch(S){case $s:return No("Suspense");case Is:return No("SuspenseList")}if(typeof S=="object")switch(S.$$typeof){case Vt:return Hu(S.render);case tn:return pp(S.type,E,O);case We:return Hu(S._render);case _l:{var G=S,Q=G._payload,re=G._init;try{return pp(re(Q),E,O)}catch{}}}return""}function mp(S){switch(S._debugOwner&&S._debugOwner.type,S._debugSource,S.tag){case C:return No(S.type);case j:return No("Lazy");case k:return No("Suspense");case U:return No("SuspenseList");case y:case x:case H:return Hu(S.type);case I:return Hu(S.type.render);case q:return Hu(S.type._render);case v:return Tg(S.type);default:return""}}function I_(S){try{var E="",O=S;do E+=mp(O),O=O.return;while(O);return E}catch(G){return` Error generating stack: `+G.message+` `+G.stack}}function nf(S,E,O){var G=E.displayName||E.name||"";return S.displayName||(G!==""?O+"("+G+")":O)}function gp(S){return S.displayName||"Context"}function _i(S){if(S==null)return null;if(typeof S.tag=="number"&&g("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."),typeof S=="function")return S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case Bn:return"Fragment";case cs:return"Portal";case or:return"Profiler";case Cn:return"StrictMode";case $s:return"Suspense";case Is:return"SuspenseList"}if(typeof S=="object")switch(S.$$typeof){case mi:var E=S;return gp(E)+".Consumer";case wt:var O=S;return gp(O._context)+".Provider";case Vt:return nf(S,S.render,"ForwardRef");case tn:return _i(S.type);case We:return _i(S._render);case _l:{var G=S,Q=G._payload,re=G._init;try{return _i(re(Q))}catch{return null}}}return null}var P_=p.ReactDebugCurrentFrame,Ca=null,wh=!1;function af(){{if(Ca===null)return null;var S=Ca._debugOwner;if(S!==null&&typeof S<"u")return _i(S.type)}return null}function ju(){return Ca===null?"":I_(Ca)}function Qa(){P_.getCurrentStack=null,Ca=null,wh=!1}function la(S){P_.getCurrentStack=ju,Ca=S,wh=!1}function gu(S){wh=S}function _p(){return wh}function kl(S){return""+S}function Xu(S){switch(typeof S){case"boolean":case"number":case"object":case"string":case"undefined":return S;default:return""}}var of={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0};function jc(S,E){of[E.type]||E.onChange||E.onInput||E.readOnly||E.disabled||E.value==null||g("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."),E.onChange||E.readOnly||E.disabled||E.checked==null||g("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")}function w_(S){var E=S.type,O=S.nodeName;return O&&O.toLowerCase()==="input"&&(E==="checkbox"||E==="radio")}function D_(S){return S._valueTracker}function G0(S){S._valueTracker=null}function pd(S){var E="";return S&&(w_(S)?E=S.checked?"true":"false":E=S.value),E}function Te(S){var E=w_(S)?"checked":"value",O=Object.getOwnPropertyDescriptor(S.constructor.prototype,E),G=""+S[E];if(!(S.hasOwnProperty(E)||typeof O>"u"||typeof O.get!="function"||typeof O.set!="function")){var Q=O.get,re=O.set;Object.defineProperty(S,E,{configurable:!0,get:function(){return Q.call(this)},set:function(ge){G=""+ge,re.call(this,ge)}}),Object.defineProperty(S,E,{enumerable:O.enumerable});var le={getValue:function(){return G},setValue:function(ge){G=""+ge},stopTracking:function(){G0(S),delete S[E]}};return le}}function Xe(S){D_(S)||(S._valueTracker=Te(S))}function pt(S){if(!S)return!1;var E=D_(S);if(!E)return!0;var O=E.getValue(),G=pd(S);return G!==O?(E.setValue(G),!0):!1}function It(S){if(S=S||(typeof document<"u"?document:void 0),typeof S>"u")return null;try{return S.activeElement||S.body}catch{return S.body}}var Ai=!1,Er=!1,Fi=!1,_r=!1;function Gs(S){var E=S.type==="checkbox"||S.type==="radio";return E?S.checked!=null:S.value!=null}function Sn(S,E){var O=S,G=E.checked,Q=h({},E,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:G??O._wrapperState.initialChecked});return Q}function qn(S,E){jc("input",E),E.checked!==void 0&&E.defaultChecked!==void 0&&!Er&&(g("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components",af()||"A component",E.type),Er=!0),E.value!==void 0&&E.defaultValue!==void 0&&!Ai&&(g("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components",af()||"A component",E.type),Ai=!0);var O=S,G=E.defaultValue==null?"":E.defaultValue;O._wrapperState={initialChecked:E.checked!=null?E.checked:E.defaultChecked,initialValue:Xu(E.value!=null?E.value:G),controlled:Gs(E)}}function ca(S,E){var O=S,G=E.checked;G!=null&&As(O,"checked",G,!1)}function Fo(S,E){var O=S;{var G=Gs(E);!O._wrapperState.controlled&&G&&!_r&&(g("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"),_r=!0),O._wrapperState.controlled&&!G&&!Fi&&(g("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"),Fi=!0)}ca(S,E);var Q=Xu(E.value),re=E.type;if(Q!=null)re==="number"?(Q===0&&O.value===""||O.value!=Q)&&(O.value=kl(Q)):O.value!==kl(Q)&&(O.value=kl(Q));else if(re==="submit"||re==="reset"){O.removeAttribute("value");return}E.hasOwnProperty("value")?cf(O,E.type,Q):E.hasOwnProperty("defaultValue")&&cf(O,E.type,Xu(E.defaultValue)),E.checked==null&&E.defaultChecked!=null&&(O.defaultChecked=!!E.defaultChecked)}function vl(S,E,O){var G=S;if(E.hasOwnProperty("value")||E.hasOwnProperty("defaultValue")){var Q=E.type,re=Q==="submit"||Q==="reset";if(re&&(E.value===void 0||E.value===null))return;var le=kl(G._wrapperState.initialValue);O||le!==G.value&&(G.value=le),G.defaultValue=le}var ge=G.name;ge!==""&&(G.name=""),G.defaultChecked=!G.defaultChecked,G.defaultChecked=!!G._wrapperState.initialChecked,ge!==""&&(G.name=ge)}function Ul(S,E){var O=S;Fo(O,E),lf(O,E)}function lf(S,E){var O=E.name;if(E.type==="radio"&&O!=null){for(var G=S;G.parentNode;)G=G.parentNode;for(var Q=G.querySelectorAll("input[name="+JSON.stringify(""+O)+'][type="radio"]'),re=0;re children."))))}),E.selected!=null&&!Rg&&(g("Use the `defaultValue` or `value` props on must be a scalar value if `multiple` is false.%s",O,Pg())}}}}function j0(S,E,O,G){var Q=S.options;if(E){for(var re=O,le={},ge=0;ge.");var G=h({},E,{value:void 0,defaultValue:void 0,children:kl(O._wrapperState.initialValue)});return G}function g3(S,E){var O=S;jc("textarea",E),E.value!==void 0&&E.defaultValue!==void 0&&!rA&&(g("%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components",af()||"A component"),rA=!0);var G=E.value;if(G==null){var Q=E.children,re=E.defaultValue;if(Q!=null){g("Use the `defaultValue` or `value` props instead of setting children on